如何将过滤器应用于 *ngFor?

编程入门 行业动态 更新时间:2024-10-28 12:19:54
本文介绍了如何将过滤器应用于 *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 { }

这是一个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?

本文发布于:2023-11-09 17:24:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   过滤器   如何将   ngFor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!