angular2 – 如何应用过滤器* ngFor

前端之家收集整理的这篇文章主要介绍了angular2 – 如何应用过滤器* ngFor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
显然,Angular2将使用管道而不是过滤器,如在Angular1中的拥塞与ng-for过滤结果,执行仍然似乎是模糊的,没有明确的文档。

也就是说,我想要实现的是从以下前提看

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

如何实现这样使用管道?

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

在您的组件:

  1. filterargs = {title: 'hello'};
  2. items = [{title: 'hello world'},{title: 'hello kitty'},{title: 'foo bar'}];

在您的模板中,您可以将字符串,数字或对象传递到您的管道以用于过滤:

  1. <li *ngFor="#item of items | myfilter:filterargs">

在你的管道:

  1. @Pipe({
  2. name: 'myfilter',pure: false
  3. })
  4. @Injectable()
  5. export class MyFilterPipe implements PipeTransform {
  6. transform(items: any[],args: any[]): any {
  7. // filter items array,items which match and return true will be kept,false will be filtered out
  8. return items.filter(item => item.title.indexOf(args[0].title) !== -1);
  9. }
  10. }

Ps。为了简单起见,我在此示例中跳过了对象输入,但是您将有一个具有id,title,date等的对象,您可以使用filterargs对象对函数应用几个检查。

猜你在找的Angularjs相关文章