javascriptangularangular2-pipe

How do I call an Angular 2 pipe with multiple arguments?


I know I can call a pipe like this:

{{ myData | date:'fullDate' }}

Here the date pipe takes only one argument. What is the syntax to call a pipe with more parameters, from component's template HTML and directly in code?


Solution

  • In your component's template you can use multiple arguments by separating them with colons:

    {{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
    

    From your code it will look like this:

    new MyPipe().transform(myData, arg1, arg2, arg3)
    

    And in your transform function inside your pipe you can use the arguments like this:

    export class MyPipe implements PipeTransform { 
        // specify every argument individually   
        transform(value: any, arg1: any, arg2: any, arg3: any): any { }
        // or use a rest parameter
        transform(value: any, ...args: any[]): any { }
    }
    

    Beta 16 and before (2016-04-26)

    Pipes take an array that contains all arguments, so you need to call them like this:

    new MyPipe().transform(myData, [arg1, arg2, arg3...])
    

    And your transform function will look like this:

    export class MyPipe implements PipeTransform {    
        transform(value:any, args:any[]):any {
            var arg1 = args[0];
            var arg2 = args[1];
            ...
        }
    }