【问题标题】:How to filter the object on typing inside the searchbar如何在搜索栏中输入内容时过滤对象
【发布时间】:2016-10-07 16:57:35
【问题描述】:

我从后端获取一个用于搜索栏的数组

当然它工作正常,但问题是我无法根据搜索栏中的用户类型进行过滤

这是我的搜索栏 html

<ion-toolbar color="primary" >
      <ion-searchbar (ionInput)="getItems($event)" (ionCancel)="onCancel($event)" [showCancelButton]="false" ></ion-searchbar>

      <ion-list *ngIf="showList">
        <ion-item *ngFor="let item of items" (click)="searchBar(item)">
          {{ item.name }}
        </ion-item>
      </ion-list>
  </ion-toolbar>
</ion-header>

这是我的 .ts 文件

getItems(ev) {
    // Show the results
     this.showList = true;


    // Reset items back to all of the items
    this.initializeItems();

    // set val to the value of the searchbar
    let val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.items = this.items.filter((item) => {

        //return item.toLowerCase().indexOf(val.toLowerCase()) > -1;
        return item;
      })
    } else {
      // Hide the results
      this.showList = false;
    }
  }

  onCancel(ev) { 
    // Show the results
    this.showList = false;

    // Reset the field
    ev.target.value = '';
  }

【问题讨论】:

  • 是用户在用户模型中键入类型字段还是objecttype
  • 我有多个对象,您可以在我的 html 内容 item 中看到这些对象,我将使用这些对象仅显示名称字段并且它正在工作,但我的问题是如果用户键入像 @ 这样的字母987654326@ 那么对象数组中与c相关的名字应该被过滤掉
  • 好的,我正在准备一个plunker。
  • 您使用的是哪个版本的 Ionic?

标签: angular autocomplete ionic2 searchbar


【解决方案1】:

您可以使用管道来实现:

@Pipe({
    name: 'filteritem'
})
export class FilterPipe implements PipeTransform{
  transform(items: any[], args: any[]): any {
        if(args !== undefined){        
          return items.filter(item => item.indexOf(args[0]) > -1);
        }
    }
}

然后您可以更改transform 的实现,以更改您希望根据输入值过滤数组的方式。

plunkr 的示例

【讨论】:

  • 我在 ionic2 中尝试过,我没有得到答案,你能不能为 ionic 2 做一个 plunker
  • 我从未使用过 ionic2,但它应该像经典的 angular2 应用一样工作,不是吗?
  • 检查这个链接 ionicframework.com/docs/v2/api/components/searchbar/Searchbar 由 ionic 团队提供,我必须使用这个你在页面右侧看到的演示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
相关资源
最近更新 更多