我在Ionic 3中开发搜索栏功能,根据插入的特定文本过滤数据。我在控制台上做了一些过滤功能测试。它可以将基于文本的数据检索到数组中。
但是,过滤后的数组没有返回显示状态。当我删除文本并卡在那里时发生了一些错误。
这是源代码: (搜索功能)
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>
感谢您的建议。
答案 0 :(得分:2)
您需要稍微修改一下过滤器功能:
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;
})
}
在您的HTML文件中:
<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>