Home » How to create custom pipe in angular

How to create custom pipe in angular

In this article, you will understand the creation of custom pipe in angular

The pipe is used to transform the values in the angular template, angular has many built-in pipes, but it has a limited feature,

if we want extra functionality or custom logic, in this condition we need to create a custom pipe.

What is pipe

If you are new to the pipe concept, will try to understand it quickly. The pipe is used to transform the values in the template, there are a few default pipes in angular as shown in below

  • DatePipe: Formats a date value according to locale rules.
  • UpperCasePipe: Transforms text to all upper case.
  • LowerCasePipe: Transforms text to all lower case.
  • CurrencyPipe: Transforms a number to a currency string, formatted according to locale rules.
  • DecimalPipe: Transforms a number into a string with a decimal point, formatted according to locale rules.
  • PercentPipe: Transforms a number to a percentage string, formatted according to locale rules.
<div>
  <!--Output: Nov 16, 2021 -->
  {{dateFormat | date:'MMM d, y'}}
</div>

Custom pipes in Angular

In pipe value transfer into new value, the value will be number, string, or array. To understand better will try to convert the hrs to minutes.

Create a simple class, give the name HrsToMinutes

export class HrsToMinutes {

}

Add decorator @Pipe to make it Pipe, import @Pipe from “@angular/core” and provide name to PipeDecorator

import { Pipe } from "@angular/core";
@Pipe({
    name:'hrsToMinutes'
})

To implement custom pipe, we need to inherit the class from PipeTransform interface and we can the transform method

export class HrsToMinutes implements PipeTransform{

    transform(){
    }
}

To convert the hrs to minutes, we need to modify the <strong>transform</strong> method in HrsToMinutes class

    transform(size:number){
        return (size*60)+" Min"
    }

To apply changes throughout the application, we need to register under the @NgModule decorator, under the declarations array

import { HrsToMinutes } from './Pipe/HrsToMinutes';

@NgModule({
  declarations: [
    ...
    HrsToMinutes
  ],

We have created the pipe, also registered under the AppModule, You can register the Pipe in your module as per your project structure. Now we can add the pipe in the template and check the changes

<div>
  <!--Output: 120 Min -->
  {{hr | hrsToMinutes}}
</div>

In the above example, the hr value is 2, giving output as 120 Min, which works perfectly.

You can download the source code from GitHub

Need help?

Read this post again, if you have any confusion or else add your questions in Community

Tags: