How to Create Custom Pipes in Angular
Posted By : Gaurav Arora | 30-Nov-2018
Hi Guys, In this blog, we will be going to create some custom pipes in Angular. First of all, we have to understand what a pipe is?
So, A Pipe is basically used to transform data, that we have to show in our HTML component. Angular has itself provide a number of default pipes, which includes Currency pipe, Date pipe, Decimal pipe, JSON pipe, Lowercase pipe, Uppercase pipe, Percent pipe, Slice Pipe and Async Pipe. These pipes will do their work but only when we have a requirement that can be fulfilled by the default pipes.
There may come some cases when we have to do some other kind of transforms. Let’s say we have a value of 20.0, In some cases, it is coming as 20 or 20.1 and we have to show it as a fixed value. In this case, we have to use toFixed() in every case. Instead of using this in every case, we can create a pipe for the same that will do our work.
So, Let’s start by creating a Pipe.
Firstly we will create a separate folder for the pipe if we don’t have any, then we have to create the component file for the same, but make sure it ends with .pipe.ts as it will be easy to understand that is a pipe file.
First, we have to import Pipe and PipeTransform from the
import { Pipe, PipeTransform } from '@angular/core';
Then we have to define the pipe name for the same, with @Pipe annotation
@Pipe({
name: 'convertToFixedValue',
})
export class FixedValuePipe implements PipeTransform {
transform(val: number): any {
return val.toFixed(2);
}
}
Now we have to import the FixedValuePipe to our app or shared module and we have to define the same in the Declarations and Exports.
import { FixedValuePipe } from 'pipe';
Now simply we have to use the pipe in the HTML as follow.
{{textToBeConverted | convertToFixedValue}}
What this pipe will do is, if we have a value of 20.1 then it will be converted to 20.10 and if we have a value of 20 then it will be shown as 20.00
So, that there will be asymmetry in the UI while displaying the values.
In this way, we can create custom pipes as per the requirement.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gaurav Arora
Gaurav is an experienced UI developer with experience and capabilities to build compelling UI's for Web and Mobile Applications.