6

I'd like to have a generic fields filter that will get the filter function as an argument and use it in filter

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

@Pipe({
  name: 'FieldsFilter'
})
@Injectable()
export class FieldsFilter implements PipeTransform {
  transform(fields: any[], args: any[]): any {
    return fields.filter(args[0]);//pass function to filter
  }
}

So I could use it in multiple places with different filter functions.

How do I pass the filter function?

naomi
  • 2,583
  • 2
  • 22
  • 39

1 Answers1

6
@Pipe({
  name: 'FieldsFilter'
})
@Injectable()
export class FieldsFilter implements PipeTransform {
  transform(fields: any[], f): any {
    return fields.filter((e) => f(e));
  }
}

it was changed quite a while ago that additional pipe parameters are passed to individual parameters instead of as single parameter in the form of an array.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    I get an error when trying to refer to `this` in the argument function. how do I bind it? – naomi Jan 12 '17 at 09:22
  • 2
    I see. Assign the function to a field in the compinent like `this.f = this.filterFuntion.bind(this);` and then pass `f` to the pipe. – Günter Zöchbauer Jan 12 '17 at 09:25
  • 1
    The advantage IMHO of `.bind(this)` is that it doesn't matter how many parameters the method supports, with `=>` you need `(a, b, c) => myFunc(a, b, c)`. I favor `=>` for inline functions though. – Günter Zöchbauer Jan 12 '17 at 09:39
  • @GünterZöchbauer thanks! but how can i use it as a filter for ngFor meaning to say that it should be to bind it to a prop and it should be invoked every time it changes? – Joe B Aug 16 '17 at 19:11
  • @JoeB it might be bettet to create a new question with some code that demonstrates what you try to accomplish. I don't get what the problem is from your comment. – Günter Zöchbauer Aug 16 '17 at 19:31
  • @GünterZöchbauer Thanks i posted a new question https://stackoverflow.com/questions/45722483/invoke-pipe-when-passing-function-as-arg-pipe-angular2 – Joe B Aug 16 '17 at 20:31