在 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/