ionic framework week 7 phone book เรียนรู้การทำ Searh bar และการ Filter Array พร้อมทั้ง Tag Tel: สำหรับให้ device โทรออก

1.เปิดโฟลเดอร์ที่ต้องการเก็บไฟล์โปรเจ็ค พิมพ์ cmd บน address bar ด้านบน
2.เมื่อ cmd เปิดมาให้พิมพ์ ionic start week7_phonebook blank
3.พิมพ์ cd week7_phonebook แล้วพิมพ์ ionic serve เพื่อเปิด serve
4.ไปที่ปุ่ม start พิมพ์ visual studio code แล้วเปิดโปรแกรมขึ้นมา เมื่อโปรแกรมเปิดขึ้นมาให้เลือกเมนู file->open folder->เลือกหา week7_phonebook ของเรา แล้วกด open
5. เข้าไปที่โฟลเดอร์ src->app->home เปิดไฟล์ home.page.html เพื่อแก้ไข
6. home.page.html
<ion-header>
<ion-toolbar>
<ion-title>
Phone Book
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<!--กล่อง search-->
<ion-searchbar (ionChange)="onSearch($event)" placeholder="ค้นหา">
</ion-searchbar>
<!--รายการเบอร์โทร-->
<ion-list>
<div *ngIf="item.length>0;else noItem">
<ion-item *ngFor="let item of item" href="tel:{{item.tel}}">
<ion-avatar slot="start">
<img src="{{item.img}}">
</ion-avatar>
<ion-label>
<h2>{{item.name}}</h2>
</ion-label>
<p>
<ion-icon name="call"></ion-icon>
{{item.tel}}
</p>
</ion-item>
</div>
<ng-template #noItem>
<ion-item>
ไม่พบข้อมูล
</ion-item>
</ng-template>
</ion-list>
</ion-content>
7.home.page.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
// ประกาศตัวแปรเก็บ ชื่อ เบอร์โทร รูปภาพ
public item:Array<{name:string,tel:string,img:string}>=[];
public allitem:Array<{name:string,tel:string,img:string}>=[];
constructor() {
this.item.push({
name:'soku',
tel:'089-923-2933',
img:'/assets/p1.jpg'
});
this.item.push({
name:'lulu',
tel:'09012345677',
img:'/assets/p2.jpg?1'
});
this.item.push({
name:'lala',
tel:'0999999999',
img:'/assets/p3.jpg?2'
});
this.allitem=this.item;
}
//เข้าสู่ฟังชั่นค้นหา
onSearch(ev: CustomEvent){
this.item=this.allitem;
//นำค่าจากกล่อง search bar มาเก็บที่ตัวแปร val
const val=ev.detail.value;
//ถ้ากล่องค้นหามีพิมพ์ค่าเข้ามาโดยไม่มีช่องว่าง
if(val!=='' && val.trim()!==''){
//ทำการค้นหาด้วยคำสั่ง filter
this.item=this.item.filter(
//ระบุขอบเขตการค้นหาด้วย term ให้ชื่อทั้งหมดเป็นตัวพิมพ์เล็กและค้นหา
term=>{
return term.name.toLowerCase()
.indexOf(val.trim().toLowerCase())>-1
}
);
}
}
}
