2015-12-22 71 views
19

我正在研究如何过滤Angular2中的数据数组。在angular2中过滤数组

我用自定义管道看了一下,但我觉得这不是我正在寻找的东西,因为它似乎更适合于简单的表示转换,而不是过滤大量数据。

阵列被设置列如下:

getLogs(): Array<Logs> { 
     return [ 
      { id: '1', plate: 'plate1', time: 20 }, 
      { id: '1', plate: 'plate2', time: 30 }, 
      { id: '1', plate: 'plate3', time: 30 }, 
      { id: '2', plate: 'plate4', time: 30 }, 
      { id: '2', plate: 'plate5', time: 30 }, 
      { id: '2', plate: 'plate6', time: 30 } 
     ]; 
    } 

我想通过id来过滤此。因此,当我在搜索栏中输入“1”时,它会更新以显示相应的值。

如果有如何做到这一点的方法,我很想知道!

回答

32

有没有办法做到这一点使用默认的管道。以下是默认支持的管道列表:https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/common_pipes.ts

这就是说,你可以轻松地添加一个管这样的用例:

import {Injectable, Pipe} from 'angular2/core'; 

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

并使用它:

import { MyFilterPipe } from './filter-pipe'; 
(...) 

@Component({ 
    selector: 'my-component', 
    pipes: [ MyFilterPipe ], 
    template: ` 
    <ul> 
     <li *ngFor="#element of (elements | myfilter:'123')">(...)</li> 
    </ul> 
    ` 
}) 

希望它可以帮助你, 蒂埃里

+0

PipeTransform的实现是做什么的?我对它的目的有点困惑。 – Witted

+0

事实上,当你想要实现一个管道时,你需要实现这个接口并把你的处理放在'transform'方法中。有关更多详细信息,请参阅相应文档:https://angular.io/docs/ts/latest/api/core/PipeTransform-interface.html。它的第一个参数对应于列表本身,第二个参数用于筛选列表中的元素... –

+0

感谢您的解释。最后一个问题是有可能将(ngf)的元素列表中的* ngFor =“#元素”作为变量的输出吗? – Witted

5

我有一个类似的场景在我的样本之一

<input "(keyup)="navigate($event)" /> 

<div *ngFor="#row of visibleRows"></div>  

...... 

navigate($event){ 
     this.model.navigate($event.keyCode); 
     this.visibleRows = this.getVisibleRows(); 
} 

getVisibleRows(){ 
    return this.model.rows.filter((row) => row.rowIndex >= this.model.start && row.rowIndex < this.model.end); 
} 

我的做法是重新计算上的一些资格赛的阵列。在我的情况下,它是keyup。绑定到函数或过滤器似乎很方便,但建议直接绑定到数组。这是因为更改跟踪会被混淆,因为每次触发更改跟踪时,函数/过滤器都会返回一个新的数组实例 - 无论触发它的是什么。

下面是完整的源代码:https://github.com/thelgevold/angular-2-samples/tree/master/components/spreadsheet

我也有一个演示:http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

+0

伊夫居然发现你的GitHub非常有帮助,所以谢谢你!我的工作表格在很大程度上基于您的网格,使用: 将数组构建到表格中。它是一个新的和稀少文件记录语言的巨大帮助。这与问题没有多大关系,但更多的是个人感谢。 – Witted

+0

谢谢!我很高兴你发现样本有帮助 – TGH

+0

“更改跟踪会变得混乱,因为每次触发更改跟踪时,函数/过滤器都会返回一个新的数组实例” - 非常正确,但是如果每次都返回相同的数组实例,你使用有状态的管道。或者,如果你的组件允许,你可以使用'onPush'变化检测策略与有状态管道一起使用。我在[This SO answer](http://stackoverflow.com/a/34497504/215945)中讨论了这两个选项。 –