在angular2中过滤数组 [英] Filtering an array in angular2
问题描述
我正在研究如何在 Angular2 中过滤数据数组.
I am looking into how to filter an array of data in Angular2.
我考虑过使用自定义管道,但我觉得这不是我想要的,因为它似乎更适合简单的表示转换,而不是过滤大量数据.
I looked into using a custom pipe, but I feel this is not what I am looking for, as it seems more geared towards simple presentation transformations rather then filtering large sets of data.
数组设置如下:
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"时,它会更新以显示相应的值.
I want to filter this by id. So when I enter "1" into a search bar, it updates to display the corresponding values.
如果有关于如何做到这一点的方法,我很想知道!
If there is a method on how to do this, I would love to know!
推荐答案
使用默认管道无法做到这一点.这是默认支持的管道列表:https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/common_pipes.ts.
There is no way to do that using a default pipe. Here is the list of supported pipes by default: https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/common_pipes.ts.
也就是说,您可以轻松地为此类用例添加管道:
That said you can easily add a pipe for such use case:
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>
`
})
希望对你有帮助蒂埃里
这篇关于在angular2中过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!