How can we create custom Pipes in angular?
There are a number of Built-in Pipes available, sometimes we may want to transform values in custom formats. Let’s check how we can create our own Pipes in an Angular application.
Create a new class which will import Pipe class and have @Pipe decorator with a meta-information name.
Run following ng command in CLI to generate a new pipe named ‘pool ‘
ng g pipe pool
Above command will add PoolPipe in the app.module.ts file’s declaration array.
The pool.pipe.ts file will look like this:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: pool
})
export class PoolPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
return null;
}
}
Change the transform method with the following to return a modified value.
transform(value: string, pooltext?: string): string {
return pooltext+"_"+value+"_"+pooltext;
}
Now we can use this Pipe in the template:
{{somePoolText | Pool:'Freaky' }}
//OUTPUT Freaky_MyPoolText_Freaky