如何将过滤器应用于* ngFor? [英] How to apply filters to *ngFor?
问题描述
显然,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 { }
这是一个柱塞,它演示了自定义过滤器管道和内置切片管道的使用限制结果.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!