以angular2过滤数组

Wit*_*ted 20 arrays filtering pipe typescript angular

我正在研究如何过滤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 }
        ];
    }
Run Code Online (Sandbox Code Playgroud)

我想通过id过滤这个.因此,当我在搜索栏中输入"1"时,它会更新以显示相应的值.

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

Thi*_*ier 36

使用默认管道无法做到这一点.以下是默认支持的管道列表: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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

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

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

希望它对你有帮助,蒂埃里


TGH*_*TGH 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);
}
Run Code Online (Sandbox Code Playgroud)

我的方法是在一些符合条件的事件上重新计算数组.就我而言,这是关键.绑定到函数或过滤器似乎很方便,但建议直接绑定到数组.这是因为更改跟踪会变得混乱,因为每次触发更改跟踪时函数/过滤器都会返回一个新的数组实例 - 无论是什么触发它.

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

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