离子搜索栏-搜索结果优先级

时间:2018-12-21 07:39:26

标签: angular ionic-framework search ionic2

我在数组中有一组物品

我们称它为fruitArray。

fruitArray = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple', 'Cherries', 'Cranberries', 'Raspberries', 'Strawberries', 'Watermelon'];

现在,我在Ionic中执行常规搜索操作。

当我在搜索框中输入值“ ap ”时,过滤后的列表将按以下顺序显示项目-

Gr ap e

Ap ple

这是常规搜索。

就我而言,我希望列表更改显示列表的顺序。

Ap ple

Gr ap e

我想显示以我的filterValue开头的数据项,然后再显示具有子字符串为我的filterValue.的数据项

谢谢。

1 个答案:

答案 0 :(得分:0)

这是一种实现方法:

在您的.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);
          }
        }
    }
}