DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Edited on

TIL: How to create a custom pipe in Angular

To build a custom pipe, just create a class that implements PipeTransfrom like this:

transform-to-space.pipe.ts

export class TransformToSpace implements PipeTransform {
  transform(value: string, symbol: string): any {
    return value.replace(symbol, ' ');
  }
}
Enter fullscreen mode Exit fullscreen mode

As the class above implements PipeTransform, we are required to implement every property/method. In this case, we need to implement the transform method.

The custom pipe we are creating takes a character and converts that to space. The final class will look something like this:

transform-to-space.pipe.ts final

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

@Pipe({
  name: 'transformToSpace'
})

export class TransformToSpace implements PipeTransform {
  transform(value: string, symbol: string): any {
    return value.replace(symbol, ' ');
  }
}
Enter fullscreen mode Exit fullscreen mode

In order to use the pipe we put this on the template like so:

<p>{{message.value | transformToSpace:'<'}}</p>
Enter fullscreen mode Exit fullscreen mode

We use the same name as assigned under

@Pipe({
  name: 'transformToSpace'
})
Enter fullscreen mode Exit fullscreen mode

Since transform takes two param: value in this case is message.value and symbol is defined after pipe name and colon like transformToSpace:'<'. And that is how you create and use a custom pipe.

Top comments (0)