Custom Pipes In Angular

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;
    }
}

Let's take a closer look at the code.

Angular Pipe and PipeTransform libraries must be imported. The Angular Core includes these libraries.
import {Pipe, PipeTransform} from '@angular/core';

The @pipe decorator is used to decorate the TempConverterPipe class. Angular recognizes the class as a pipe thanks to the @pipe decorator. The decorator expects us to give the pipe a name. It's been given the name tempConverter. To make use of this pipe, we must use this name in the template.

The PipeTransform interface must be implemented by our class.
@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
}

The value of the first parameter is the value that the pipe must alter. We can also incorporate as many arguments as we want. The altered data must be returned by the method.

The transform method is implemented in the following way. Value is the first, while Unit is the second. The unit expects either C (convert to Celsius) or F (convert to Fahrenheit) ( convert to Fahrenheit). Based on the Unit, it transforms the value obtained to Celsius or Fahrenheit.
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 we can use our pipe, we must first tell our component where to look for it. This is accomplished by first importing it and then included it in the AppModule's declarations array.
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 similarly to the Angular built-in pipes. In your app, add the following code in app.component.html file.
<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;   
}

Now run the application and check browser screen looks like below


Example of Custom Pipe In Angular


Conclusion

In this article, we learned how to create an Angular Custom Pipe and how to use it. In next article we learn KeyValue Pipe In Angular.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post