In Angular2, I have a text filter pipe below. Instead of fixing "title", is it possible to pass in the property name which the data are filtered by?
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);
}
}
Yes, you can use several parameters:
@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);
}
}
And use it this way:
someArray | textfilter:title:value
Note that you don't need to use the @Injectable
decorator with pipes.
RC.x version
@Pipe({
name: 'textfilter'
})
export class TextFilterPipe implements PipeTransform {
transform(items: any[], filterProp, filterValue): any {
return items.filter(item => item.[filterProp].indexOf(filterValue) !== -1);
}
}
and use it like
{{someValue | textfilter:'title':abcde}}
beta.x version
@Pipe({
name: 'textfilter'
})
export class TextFilterPipe implements PipeTransform {
transform(items: any[], args: any[]): any {
return items.filter(item => item.[args[0]].indexOf(args[1]) !== -1);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With