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

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

问题描述

我正在寻找 angular 2 方法来做这个.

我只有一个项目列表,我想输入一个过滤列表的内容.

<md-input placeholder="项目名称..." [(ngModel)]="name"></md-input><div *ngFor="let item of items">{{项目名称}}

在 Angular 2 中这样做的实际方法是什么?需要管道吗?

解决方案

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

标记 - HTML 模板

<md-input #myInput placeholder="项目名称..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-输入><div *ngFor="let item of filtersItems">{{项目名称}}

代码

assignCopy(){this.filteredItems = Object.assign([], this.items);}过滤器项目(值){如果(!值){this.assignCopy();}//当什么都没有输入时this.filteredItems = Object.assign([], this.items).filter(项目 =>item.name.toLowerCase().indexOf(value.toLowerCase()) >-1)}this.assignCopy();//当你从服务器获取集合时.

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>

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

解决方案

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.

Markup - HTML Template

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

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

Code

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天全站免登陆