Custom Pipes

Sometimes you may need specific transformations, in which the default Angular Pipes won’t be enough. That’s when Custom Angular Pipes take place, which allows you to create your own pipe, specifying the input, the transformation function and the output.

1. Creating a Custom Pipe

First we are going to create our pipe. This will be a very simple one just for explanation, in which we are going to provide a string parameter which is going to be concatenated to a Hello. We do it like the following:

import { Pipe, PipeTransform } from ' @angular/core ';

name: 'sayHello'

})

export class GreetingsPipe implements PipeTransform { @Pipe ({name: 'sayHello'})export class GreetingsPipe implements PipeTransform { public transform(name: string): string {

return 'Hello, ' + name;

} }

The name specified in the @Pipe decorator is the name of the pipe that will be used in the HTML, like date, lowercase, uppercase, etc.

The transform function is where the magic happens, where you actually do the desired transformation on the received input. On the example above, we are receiving one input parameter (a name string), which is the value which we are going to apply the transform function. The first parameter in the transform function is always the value we are going to work with.

However we can receive as many parameters as we’d like, in case we need themn. We would then provide them in the HTML and be able to use them in the transform function, as we are going to see further. Finally, our transform function returns a string, which is going to be our pipe’s output.

2. Registering a Custom Pipe

Then, in order to use it we are going to register it. To register a Pipe, all you have to do is add its class to a module declarations. Here we are also going to create a module for that pipe and export it to be used in other modules.

import { NgModule } from '@angular/core';

import { GreetingsPipe } from './greetings.pipe'; @NgModule({

declarations: [

GreetingsPipe

],

exports: [

GreetingsPipe

]

})

export class GreetingsPipeModule { }

3. Using a Custom Pipe

Once you have your pipe created, registered in a module and have that module imported where you will need it, your pipe is ready to be used!

Supposing we have an user object in our component with a property firstName, which is a string containing the user’s first name. Then, we could add to our HTML a paragraph to greet our user, like shown bellow: