10

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

1 Answer 1

10

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.