如何对 \*ngFor 应用过滤器?

新手上路,请多包涵

显然,Angular 2 将使用管道而不是 Angular1 中的过滤器,并结合 ng-for 来过滤结果,尽管实现似乎仍然模糊,没有明确的文档。

即可以从以下角度看待我想要实现的目标

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

如何使用管道来实现?

原文由 Khaled 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 916
2 个回答

基本上,您编写一个管道,然后您可以在 *ngFor 指令中使用它。

在您的组件中:

 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 中注册您的管道;您不再需要在您的 @Component 中注册管道

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        MyFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

这是一个 Plunker ,它演示了使用自定义过滤器管道和内置切片管道来限制结果。

请注意(正如几位评论员所指出的)Angular 中没有内置过滤器管道 是有原因 的。

原文由 phuc77 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以这样做:

 <ng-container *ngFor="item in items">
    <div *ngIf="conditon(item)">{{ item.value }}</div>
</ng-container>

或者

<div *ngFor="item in items">
  <ng-container *ngIf="conditon(item)">{{ item.value }}</ng-container>
</div>

原文由 Hoan Danh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进