显然,Angular 2 将使用管道而不是 Angular1 中的过滤器,结合 ng-for 来过滤结果,尽管实现似乎仍然模糊不清,没有明确的文档.
Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, with no clear documentation.
也就是说,我想要实现的目标可以从以下角度来看
Namely what I'm trying to achieve could be viewed from the following perspective
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>如何使用管道来实现?
推荐答案基本上,您编写一个管道,然后您可以在 *ngFor 指令中使用它.
Basically, you write a pipe which you can then use in the *ngFor directive.
在您的组件中:
filterargs = {title: 'hello'}; items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];在您的模板中,您可以将字符串、数字或对象传递给管道以用于过滤:
In your template, you can pass string, number or object to your pipe to use to filter on:
<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 中注册你的管道;您不再需要在 @Component
Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component
import { MyFilterPipe } from './shared/pipes/my-filter.pipe'; @NgModule({ imports: [ .. ], declarations: [ MyFilterPipe, ], providers: [ .. ], bootstrap: [AppComponent] }) export class AppModule { }这是一个Plunker,它演示了自定义过滤器管道和内置切片管道的使用限制结果.
Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.
请注意(正如几位评论员指出的那样)有一个原因 为什么 Angular 没有内置过滤器管道.
Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.
更多推荐
如何将过滤器应用于 *ngFor?
发布评论