在angular2中过滤数组

Filtering an array in 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”时,它会更新以显示相应的值。

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

我的一个样本中有类似的情况

<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。绑定到函数或过滤器似乎很方便,但建议直接绑定到数组。这是因为更改跟踪会变得混乱,因为每次触发更改跟踪时 function/filter 都会 return 一个新的数组实例 - 无论触发它的是什么。

这是完整的来源:https://github.com/thelgevold/angular-2-samples/tree/master/components/spreadsheet

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

使用默认管道无法做到这一点。以下是默认支持的管道列表: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>
  `
})

希望对你有帮助, 蒂埃里