How to create custom pipes in Angular

Pankaj Kumar - Dec 19 '19 - - Dev Community

While working with Angular, The situation occurs many times to change the format of the data we are trying to show in HTML template. There are some in-built pipes provided by angular itself like below:

  1. DatePipe (for parsing Date objects)
  2. UpperCasePipe (for uppercase-ing Strings)
  3. LowerCasePipe (for lowercase-ing Strings)
  4. CurrencyPipe (for formatting currencies)
  5. AsyncPipe (for unwrapping asynchronous values, such as Observables!)

Apart from the in-built pipes, Custom pipes can also be created to achieve any specific requirement.

Here I am going to explain one example to show you how a custom pipe can be created. Here we will use the created pipe to reverse any number.

Let's Get Started.

Step 1: Create pipe(a file named reverse-string.pipe.ts)

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

@Pipe({name: 'reverseString'})
export class ReverseString implements PipeTransform {
transform(value: string): string {
let newStr: string = "";
for (var i = value.length - 1; i >= 0; i--) {
newStr += value.charAt(i);
}
return newStr;
}
}

Step 2: Add this pipe in app.module.ts file.

import { ReverseStr } from './reverse-string.pipe.ts';
.......
......

@NgModule({
declarations: [
........,
ReverseStr,
.......
],
......
......
})

Step 3: Use the pipe in template

item.first_name | ReverseString

Pipe with Multi arguments

In any case we want to append/ or add deduct some value from the available data then multiple arguments can also be passed using below way:

myData | date:'fullDate':'arg1':'arg2'

export class DatePipe implements PipeTransform {

transform(value:any, arg1:any, arg2:any):any {
...
}

Interested to find more blogs on Angular, Read at https://jsonworld.com/blog

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .