How to implement searching and filtering in Ionic
You are doing it wrong.
- You do
return this.data.filter(...)
. It has no effect to your origin array (this.data
). It just return a new array and does not make change tothis.data
. See the filter function doc - If you want to make change to your data you need to add:
this.data = this.data.filter(...)
. But if you do like that, you will fall in other mistake. Yourthis.data
will lost some element after filter and it can not be revert when you reset the filter.
So you should do like that:
In your component:
allData = []; //Store all data from provider
filterData = [];//Store filtered data
ionViewDidEnter(){
this.allData = this.locations.data;
this.filterData = this.allData;
}
setFilteredLocations(){
this.filterData = this.allData.filter((location) => {
return location.title.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
});
}
And in your template use filterData in ngFor
:
<button ion-item *ngFor="let location of filterData">
Yo didn't send the $event
here. So try as shown below.
.html
<ion-searchbar [(ngModel)]="searchTerm"
(ionInput)="setFilteredLocations($event)"></ion-searchbar>
.ts
setFilteredLocations(ev: any){
let val = ev.target.value;
if (val && val.trim() !== '') {
return this.locations.filterLocations(val);
}
}
You can see the official sample code here.