Reputation: 525
I'm developing search bar function in Ionic 3 to filter the data based on specific text inserted. I did some testing on console for filter function. It works to retrieve data based on text into array.
However, the filtered array didn't return into display. Some more error occurred when i deleted text and stuck there.
Here is the testing on browser console: (full data)
Here is source code: (Search Function)
public food:any;
queryText: string;
updateText(){ //this is filter text function
let queryTextLower = this.queryText.toString().toLowerCase(); //convert to lower case
let filterFood = []; //to store array of filtered food
let food = _.filter(this.food,t => (<any>t).name.toLowerCase().includes(queryTextLower));
if (food.length) {
filterFood.push( {food} );
}
console.log(filterFood); // testing display on console
this.food = filterFood;
}
HTML code:
<ion-toolbar>
<ion-searchbar aria-placeholder="search"
[(ngModel)]="queryText"
(ionInput)="updateText()">
</ion-searchbar>
</ion-toolbar>
<ion-item >
<ion-label>Name</ion-label>
<ion-label>Description</ion-label>
<ion-label>Price</ion-label>
</ion-item>
<ion-item *ngFor="let item of food" >
<ion-label style="width: 40px; height: 80px;" >{{item.name}} </ion-label>
<ion-label style="width: 40px; height: 80px;" >{{item.description}} </ion-label>
<ion-label style="width: 40px; height: 80px;" >{{item.price}} </ion-label>
</ion-item>
Thanks for advice.
Upvotes: 0
Views: 459
Reputation: 458
You need to modify a little your filter function:
updateText()(){
if (this.queryText == ""){
this.filtered = this.food; // Original array with food elements can be [] also
}
else{
this.filtered = this.food.filter((fd) => {
return fd.toLowerCase().indexOf(this.queryText.toLowerCase()) > -1;
})
}
And in your HTML file:
<ion-toolbar>
<ion-searchbar aria-placeholder="search"
[(ngModel)]="queryText"
(ionInput)="updateText()">
</ion-searchbar>
</ion-toolbar>
<ion-item >
<ion-label>Name</ion-label>
<ion-label>Description</ion-label>
<ion-label>Price</ion-label>
</ion-item>
<ion-item *ngFor="let item of filtered" >
<ion-label style="width: 40px; height: 80px;" >{{item.name}} </ion-label>
<ion-label style="width: 40px; height: 80px;" >{{item.description}} </ion-label>
<ion-label style="width: 40px; height: 80px;" >{{item.price}} </ion-label>
</ion-item>
Upvotes: 2