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

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

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

发布评论

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

>www.elefans.com

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