Passing angular pipe as a string

angular pipe typescript

Introduction

In this tutorials we will walk through how pass pipe (whether its custom pipe, or an angular build it in pipe ) using the string name of the pipe.

Requirements

The inspiration of this tutorial come while I was developing the 'ng-x-libray' where I have a table that get rendered based on passed in data and a columns configuration. The columns configuration have pipe property which takes a string name of a pipe that will be applied to the data. You can have a look at ng-x-table library

want is to create a generic pipe that take a pipe name as string and apply the pipe in question like so:

<p>{{ 100 | getPipe: 'currency' }}</p>

Implementation

We will use the cli to create the pipe name 'getPipe' and to keep it simple we will skip the spec, i.e. test, file generation

$ ng g p get --spec=false

Open the the get.pipe.ts file.

First let's change the name of the pipe from 'get' to 'getPipe'.

Then in the transform function let's change the second args from 'args' to 'pipeName' and change its type to string.

We need to check for the value of pipeName when it's null we simply return the `value`.

Now the interesting part

We will use the injector to get the class of the pipe from its string

const pipe = this.injector.get<PipeTransform>(<any>pipeName, <any>{});

We are not out the water yet, being a good developer we need to check if the pipe constant has property transform and it's of type function.

When these two condition are true we apply the transform function on the value passed to the 'getPipe' pipe otherwise we return the value.

if (pipe.transform && typeof pipe.transform === 'function') {
    return (pipe.transform(value));
} else {
    return value;
}

The catch

This won't work just yet, we need to provide the pipe that we going to pass as a string.

Allow me explain

For angular to be able to get the pipe from its string name using the injector (see code above) we need to provide it for angular.

Lets assume we need to use the currency pipe (build it pipe courtesy of angular). We should add the following line to the providers property of the app module

providers: [
    { provide: 'currency', useClass: CurrencyPipe },
]

`Provide` property is the string we gonna pass to the getPipe and `useClass` is the class of the currency pipe.

For completion let's create a pipe that round down number, we call this pipe 'roundDown'.

$ ng g p roundDown --spec=false

I will leave out the implementation of the `roundDownPipe` as it out of the scope of this tutorial.

To use `roundDownPipe` this with the getPipe we add it to the array of providers in the app module.

providers: [
    { provide: 'currency', useClass: CurrencyPipe },
    { provide: 'roundDown', useClass: RoundDownPipe }
]

Then wee can simply use it in the template like so:

<p>{{ 100.75 | getPipe: 'roundDown' }}</p>