How to pass function as arg Pipe angular2
Asked Answered
I

1

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?

Isagoge answered 12/1, 2017 at 8:52 Comment(0)
L
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.

Labors answered 12/1, 2017 at 8:59 Comment(6)
I get an error when trying to refer to this in the argument function. how do I bind it?Isagoge
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.Barbule
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.Barbule
@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?Boldt
@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.Barbule
@GünterZöchbauer Thanks i posted a new question #45722983Boldt

© 2022 - 2024 — McMap. All rights reserved.