Custom Pipes In Angular
In this article, we will learn how to create Angular Custom Pipe. Pipes are a fantastic technique to change the appearance of items in a template. The Angular framework has some useful built-in pipes, such as a Date pipe, a Currency pipe, and a Number pipe, among others. However, if these pipes do not meet your requirements, we can write our own custom pipe in Angular.
To make a bespoke pipe, we must first make a pipe class. The PipeTransform interface must be implemented by the pipe class. We also used @pipe decorator to dress it up. Give the pipe a name using the @pipe decorator name metadata. Finally, the transform method is created, which changes a supplied value into the desired output.
How to Create Custom Pipes
You must first follow these steps in order to establish a Custom Pipe.
- Create a class for pipes.
- Use the @pipe decorator to add some flair to the class.
- In the @pipe decorator name meta data, give the pipe a name. This is the name that will be used in the template.
- The PipeTransform interface must be implemented by the pipe class. There is only one method transform in the interfaces.
- The value to be transferred is the transform method's first parameter. The value must be transformed and the result must be returned by the transform method. The transform method can take any number of additional arguments.
- In the Angular Module, declare the pipe class (app.module.ts)
- Use the custom pipe in the same way as you would any other pipe.
Example
Create an Angular application from scratch. If you're new to Angular, start with the Create Angular Application article.
For styling, we're use Bootstrap 4. As a result, open index.html and add the following code.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
Make a new temp-convertor.pipe.ts file. In the src/app folder. Use following command for create new pipe:
ng g pipe temp-convertor
Now, Open the temp-convertor.pipe.ts file and add the following code.
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; } }
import {Pipe, PipeTransform} from '@angular/core';
@pipe({ name: 'tempConverter' }) export class TempConverterPipe implements PipeTransform { }
There is only one method transform defined in the PipeTransform interface. The following is the interface definition.
interface PipeTransform { transform(value: any, ...args: any[]): any }
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
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
<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>
The following is how we use our pipe. The first given value to the tempConverter is Fahrenheit. To indicate that the tempConverter is a conduit to angular, we use the | (pipe) symbol. The first argument is the C following the colon. By using a : colon to separate each parameter, you can pass several arguments to the pipe.
{{Fahrenheit | tempConverter:'C'}}
Using the TempConverter Pipe in Template. Add the following code to the app.component.ts file
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;
}