In this tutorial, we will show you how to create an Angular Custom Pipe. The Pipes are a great way to transform the appearance of elements in the template. The Angular comes with some great built-in pipes like Date pipe, Currency pipe, and Number pipe, etc. But if these pipes do not cover your needs, then we can create our own pipe in Angular.
To create a custom pipe, first we need to create a pipe class. The pipe class must implement the PipeTransform
interface. We also decorate it with @pipe
decorator. Give a name
to the pipe under name
metadata of the @pipe
decorator. Finally, we create the transform
method, which transforms given value to the desired output.
Table of Contents
How to Create Custom Pipes
To create a Custom Pipe, first, You need to follow these steps
- Create a pipe class
- Decorate the class with
@pipe
decorator. - Give a name to the pipe in the
name
meta data of the@pipe
decorator. We will use this name in the template. - The pipe class must implement the
PipeTransform
interface. The interfaces contain only one methodtransform
. - The first parameter to the
transform
method is the value to be transferred. Thetransform
method must transform the value and return the result. You can add any number of additional arguments to thetransform
method. - Declare the pipe class in the Angular Module (app.module.ts)
- Use the custom pipe just as you use other pipes.
Now let us create a Temperature converter pipe, which converts temperature from Celsius to Fahrenheit and vice versa.
Temparature Convertor Custom Pipe Example
Create a new Angular application. If you are new to Angular you can refer to the tutorial Create Angular Application.
We are using bootstrap 4 for styling. Hence open the index.html
and add the following
1 2 3 | <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> |
Create a new file temp-convertor.pipe.ts
. Under the folder src/app
. Copy the following code and paste it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import {Pipe, PipeTransform} from '@angular/core'; @pipe({ name: 'tempConverter' }) export class TempConverterPipe implements PipeTransform { transform(value: number, unit: string) { if(value && !isNaN(value)) { if (unit === 'C') { var temperature = (value - 32) /1.8 ; return temperature.toFixed(2); } else if (unit === 'F'){ var temperature = (value * 1.8 ) + 32 return temperature.toFixed(2); } } return; } } |
Let us look at the code in details
We need to import the Pipe
& PipeTransform
libraries from Angular. These libraries are part of the Angular Core
1 2 3 | import {Pipe, PipeTransform} from '@angular/core'; |
We decorate TempConverterPipe
class with @pipe
decorator. The @pipe decorator is what tells Angular that the class is a pipe. the decorator expects us to provide a name to the pipe. We have given it as tempConverter
. This is the name we must use in the template to make use of this pipe.
Our class must implement the PipeTransform
interface.
1 2 3 4 5 6 7 8 9 | @pipe({ name: 'tempConverter' }) export class TempConverterPipe implements PipeTransform { } |
The PipeTransform
interface defines only one method transform
. The interface definition is as follows.
1 2 3 4 5 | interface PipeTransform { transform(value: any, ...args: any[]): any } |
The first argument value is the value, that pipe needs to transform. We can also include any number of arguments. The method must return the final transformed data.
The following is Our implementation of the transform
method. The first is Value
and the second is the Unit
. The unit
expects either C
(Convert to Celsius) or F
( convert to Fahrenheit). It converts the value received to either to Celsius or to Fahrenheit based on the Unit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | export class TempConverterPipe implements PipeTransform { transform(value: number, unit: string) { if(value && !isNaN(value)) { if (unit === 'C') { var temperature = (value - 32) /1.8 ; return temperature.toFixed(2); } else if (unit === 'F'){ var temperature = (value * 1.8 ) + 32 return temperature.toFixed(2); } } return; } } |
Declare the Pipe
Before using our pipe, we need to tell our component, where to find it. This is done by first by importing it and then including it in declarations array of the AppModule
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import {TempConverterPipe} from './temp-convertor.pipe'; @NgModule({ declarations: [AppComponent,TempConverterPipe], imports: [BrowserModule,FormsModule,HttpModule], bootstrap: [AppComponent] }) export class AppModule { } |
Using the Custom Pipe
The custom pipes are used in the same as the Angular built-in pipes are used. Add the following HTML code to your app.component.html
file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <div class='card'> <div class='card-header'> <p>{{title}} </p> </div> <div class="card-body"> <div class="row"> <h3>Fahrenheit to Celsius </h3> </div> <div class="row"> <p> Fahrenheit : <input type="text" [(ngModel)]="Fahrenheit" /> Celsius : {{Fahrenheit | tempConverter:'C'}} </p> </div> <div class="row"> <h3>Celsius to Fahrenheit </h3> </div> <div class="row"> <p> celsius : <input type="text" [(ngModel)]="celcius" /> Fahrenheit : {{celcius | tempConverter:'F'}} </p> </div> </div> </div> |
We use our pipe as follows. Fahrenheit
is sent to the tempConverter
as the first argument value
. We use the |
to indicate that the tempConverter
is a pipe to angular. The C
after the colon is the first argument. You can pass more than argument to the pipe by separating each argument by a :
colon.
1 2 3 | {{Fahrenheit | tempConverter:'C'}} |
app.component
code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title: string = 'Angular Custom Pipe Example' ; celcius: number; Fahrenheit: number; } |
Run the application and test it. I
Reference
Read More
There is type in @pipe, here P shoulb be in caps
I think it is better to show the description and code side-by-side, so that it is easier to understand while reading.
Showing error in tempConvertor
change pipe decorator from @pipe to @Pipe. Hope this will help
nice
change the pipe decorator from @pipe to @Pipe
Good one….
good tutorial and explaination.