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

也就是说,我想要达到的目标可以从以下角度来看待

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

如何实现这样使用管道?


当前回答

Angular2中的管道类似于命令行中的管道。前面每个值的输出在管道之后被送入过滤器,这使得链过滤器很容易,就像这样:

<template *ngFor="#item of itemsList">
    <div *ngIf="conditon(item)">{item | filter1 | filter2}</div>
</template>

其他回答

很多人都有很好的方法,但这里的目标是通用的和定义的数组管道,它在与*ngFor相关的所有情况下都是非常可重用的。

ts(不要忘记将其添加到模块的声明数组中)

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
    name: 'callback',
    pure: false
})
export class CallbackPipe implements PipeTransform {
    transform(items: any[], callback: (item: any) => boolean): any {
        if (!items || !callback) {
            return items;
        }
        return items.filter(item => callback(item));
    }
}

然后在您的组件中,您需要实现一个具有以下signature (item: any) => boolean的方法,例如,在我的示例中,我将其称为filterUser,用于过滤大于18岁的用户的年龄。

您的组件

@Component({
  ....
})
export class UsersComponent {
  filterUser(user: IUser) {
    return !user.age >= 18
  }
}

最后,你的html代码看起来是这样的:

HTML

<li *ngFor="let user of users | callback: filterUser">{{user.name}}</li>

正如您所看到的,这个Pipe对于所有需要通过回调筛选的数组(如项目)都是相当通用的。在我的例子中,我发现它对于*ngFor之类的场景非常有用。

希望这能有所帮助!!

codematrix

这是我不久前创建的一个例子,并在博客上发表过,其中包括一个工作的扑通。它提供了一个过滤管道,可以过滤任何对象列表。基本上你只需要在ngFor规范中指定属性和值{key:value}。

这与@NateMay的回复没有太大不同,只是我比较详细地解释了它。

在我的例子中,我过滤了一个无序列表的一些文本(filterText),用户输入针对对象的“label”属性在我的数组中使用这种标记:

<ul>
  <li *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
</ul>

https://long2know.com/2016/11/angular2-filter-pipes/

下面给出了限制ngFor的最简单易行的方法

<li *ngFor="let item of list | slice:0:10;Let i=index" class="dropdown-item" >{{item.text}}</li> .text}

这是我的代码:

import {Pipe, PipeTransform, Injectable} from '@angular/core';

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value): any[] {
      if (!items) return [];
      if (!value || value.length === 0) return items;
      return items.filter(it =>
      it[field] === value);
    }
}

示例:

LIST = [{id:1,name:'abc'},{id:2,name:'cba'}];
FilterValue = 1;

<span *ngFor="let listItem of LIST | filter : 'id' : FilterValue">
                              {{listItem .name}}
                          </span>

在Angular 6中过滤ngFor的一个简单解决方案如下:

<span *ngFor="item of itemsList" > < div * ngIf = " yourCondition(项)" > 你的代码 < / div > < / span >

span很有用,因为它本身并不代表任何东西。