Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass function as arg Pipe angular2

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?

like image 717
naomi Avatar asked Jan 12 '17 08:01

naomi


People also ask

How do you pass a pipe function?

To use a pipe, you simply append a Pipe character to the end of a string interpolation and then the name of the pipe. In this case, the date pipe. You can also pass the format to be used by the Date transformation process, inside the Date pipe by appending a Colon after the pipe name and specifying the format.

How do you pass multiple arguments to a pipe?

In your component's template you can use multiple arguments by separating them with colons: {{ myData | myPipe: 'arg1':'arg2':'arg3'... }} Pipes take an array that contains all arguments, so you need to call them like this: new MyPipe().

Can we pass parameters to pipe in Angular?

You can easily pass multiple arguments in pipe in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. In this example we will create 'descPipe' custom pipe and create dynamic description with multiple parameters.

What does pipe () Do Angular?

Use pipes to transform strings, currency amounts, dates, and other data for display. Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.


1 Answers

@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.

like image 72
Günter Zöchbauer Avatar answered Nov 15 '22 09:11

Günter Zöchbauer