Angular 內置了一些管道,好比 DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe 和 PercentPipe。 它們全均可以直接用在任何模板中;可是在angular(angular2)中因爲性能的緣由官方沒有提供有關篩選和排序的管道,因而當咱們在使用
*ngFor
須要篩選數據時能夠自定義篩選管道。html
filterargs = {title: 'hello'}; items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
<li *ngFor="let item of items | myfilter:filterargs">
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myfilter', pure: false }) export class MyFilterPipe implements PipeTransform { transform(items: any[], filter: Object): any { if (!items || !filter) { return items; } // filter items array, items which match and return true will be // kept, false will be filtered out return items.filter(item => item.title.indexOf(filter.title) !== -1); } }
app.module.ts
; you no longer need to register the pipes in your @Component
import { MyFilterPipe } from './shared/pipes/my-filter.pipe'; @NgModule({ imports: [ .. ],C declarations: [ MyFilterPipe, ], providers: [ .. ], bootstrap: [AppComponent] }) export class AppModule { }
參考連接:bootstrap
https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngforangular2