Angular 2 : pass in a property name to a pipe

标签 angular

在 Angular2 中,我在下面有一个文本过滤器管道。除了固定“标题”之外,是否可以传入过滤数据所依据的属性名称?

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

@Pipe({
  name: 'textfilter'
})
@Injectable()
export class TextFilterPipe implements PipeTransform {
  transform(items: any[], args: any[]): any {
    return items.filter(item => item.title.indexOf(args[0]) !== -1);
  }
}

最佳答案

是的,你可以使用几个参数:

@Pipe({
  name: 'textfilter'
})
export class TextFilterPipe implements PipeTransform {
  transform(items: any[], args: any[]): any {
    var paramName = args[0];
    var paramValue = args[1];
    return items.filter(item => item[paramName].indexOf(paramValue) !== -1);
  }
}

并以这种方式使用它:

someArray | textfilter:title:value

请注意,您不需要将 @Injectable 装饰器与管道一起使用。

关于 Angular 2 : pass in a property name to a pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37157098/

相关文章:

javascript - Angular 单元测试: How to unit test subscription inside ngOnInIt()?

javascript - Angular 2 : How do I achieve selectability of a specific route config list based on a external value

Angular 7 'Access-Control-Allow-Origin' header 包含多个值

javascript - tensorflow JS : TypeError: Cannot read property 'fetch' of undefined

javascript - 使用 Angular 7 中的单个提交按钮创建具有动态表单字段的动态表单

angular - 在 Angular 中创建可重用的按钮组件

angular - TensorflowJS : Error: The shape of dict ['images' ] provided in model. execute(dict) 必须是 [-1,224,224,3],但是是 [400,600,1]

angular - tsconfig.spec.json 有什么作用?

angular - 如何在 Angular 中生成 UUID

html - 如何将 Material 图标和标题文本对齐在同一行?