这是一种方法:
在您的 .html 中,添加搜索栏
<ion-toolbar class="subtoolbarsearch">
<ion-searchbar autocorrect="true" placeholder="Look for a fruit" [(ngModel)]="search" (ionInput)="getItems($event)"></ion-searchbar>
</ion-toolbar>
在您的 .ts 中,使用 2 个变量,一个包含所有水果和搜索栏的 ngModel
public fruits;
public search: string = "";
添加一个设置水果的函数
getFruits(){
this.fruits = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple'];
}
从你的构造函数调用 if 来初始化 fruits 类变量
最终在搜索栏输入时触发的函数
getItems(ev) {
this.getFruits(); // Display all the fruits
let val = ev.target.value; // Getting the input
// If searchbar is empty, do nothing
if (val && val.trim() != '') {
// Remove unmatching fruits
for (let i = 0; i < this.fruits.length; i++) {
let pos1 = this.fruits[i].toLowerCase().indexOf(val.toLowerCase());
if (pos1 == -1) {
this.fruits.splice(i, 1); // If substring not found, we remove the fruit from displayFruits
i--; // Do not forget to decrement i by one since we removed one element from the array
}else if(pos1 == 0){
// If substring is at the beginning of the fruit name, we remove the fruit from the array, and we add it at the beginning of it
let fruit = this.fruits[i];
this.fruits.splice(i,1);
this.fruits.unshift(fruit);
}
}
}
}