Search code examples
angularangular-pipe

Angular - pass pipe as variable


How may I store and use pipe information from variables?

I've already searched a lot but couldn't find a solution for that.

What I'm trying to achieve is passing any valid pipe information as a variable (decimal, percent, date, custom, etc). Follows a simple example:

parent.component.ts:

columnsDef = {
  value: 0.35,
  pipeInfo: 'percent:"0.2-2":"pt-BR"'
};

parent.component html:

<app-display-component [columnsDef]="columnsDef"></app-display-component>

app-display.component html:

<h1> {{ columnsDef.value | columnsDef.pipeInfo }}</h1>

The expected output is the value formatted as a percentage, but all I get is a template parse error:

ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Unexpected token '.'


Solution

  • You can create a custom pipe which gets another pipe as an argument and apply it to the value given to it.

    Here is an example of a dynamic pipe created by @balu in this answer. See the link for more info.

    import {
        Injector,
        Pipe,
        PipeTransform
    } from '@angular/core';
    
    
    @Pipe({
      name: 'dynamicPipe'
    })
    export class DynamicPipe implements PipeTransform {
    
        public constructor(private injector: Injector) {
        }
    
        transform(value: any, pipeToken: any, pipeArgs: any[]): any {
            if (!pipeToken) {
                return value;
            }
            else {
                let pipe = this.injector.get(pipeToken);
                return pipe.transform(value, ...pipeArgs);
            }
        }
    }