Angular 2过滤器/搜索列表 [英] Angular 2 filter/search list

查看:168
本文介绍了Angular 2过滤器/搜索列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有角度的2种方法来做.

I'm looking for the angular 2 way to do this.

我只是有一个项目列表,我想输入谁的工作是过滤列表.

I simply have a list of items, and I want to make an input whos job is to filter the list.

<md-input placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of items">
{{item.name}}
</div>

在Angular 2中执行此操作的实际方法是什么?这需要管道吗?

What's the actual way of doing this in Angular 2? Does that requires a pipe?

推荐答案

您每次必须通过使监听器保持在input事件上,才能根据输入的更改手动过滤结果.在进行手动过滤时,请确保您应维护两个变量副本,一个将是原始集合副本&第二个是filteredCollection副本.这样做的好处是可以节省变更检测周期上的不必要的过滤.您可能会看到更多代码,但这将对性能更加友好.

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

标记-HTML模板

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

代码

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

这篇关于Angular 2过滤器/搜索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆