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, ' ');
}
}
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, ' ');
}
}
In order to use the pipe we put this on the template like so:
<p>{{message.value | transformToSpace:'<'}}</p>
We use the same name as assigned under
@Pipe({
name: 'transformToSpace'
})
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)