Custom Pipe Example In Angular.

This tutorial will show you how to create an Angular Custom Pipe. It is handy if we want to reuse some logic across our applications. It allows us to change the format in which data is displayed on the pages. For instance, consider the date of birth as 01-01-2024 and we want to display it as 01-January-2023. To achieve this we will make one pipe that can be used anywhere in our application. In angular

Types of Pipe.

 Pure Pipe.
 Impure pipes.

Pure Pipe.

The pure pipe is a pipe called when a pure change is detected in the value. It is called fewer times than the latter.

Impure Pipes.

This pipe is often called after every change detection. Be it a pure change or not, the impure pipe is called repeatedly.

Steps to Create Pipe

Below are the steps to create the custom pipe.

Create a pipe class.
Decorate the class with the @Pipe decorator.
Give a pipe name under name metadata in @Pipe decorator.
Implement the PipeTransform interface and it will contain only one method that is transform.
The transform method must transform the value and return the result.
Import the pipe class in the component.
Use the custom pipe by its name in the HTML file.

Example.

Create a pipe class and add the below code.

import { Pipe,PipeTransform } from ‘@angular/core’;

@Pipe({
name: ‘custompipe’,
standalone: true,
})

export class custompipePipe implements PipeTransform {

monthNumbers:any = [‘January’,’February’,’March’,’April’,’May’,’June’,’July’,’August’,’September’,’October’,’November’,’December’];
transform(value: any) {
let date = value.split(/[.,/ -]/);
if(date[1]>12 || date[1]<1 || isNaN(date[1])){
return “Invalid Month”;
}else{
date[1] = this.monthNumbers[date[1]-1];
return date.join(‘-‘);
}

}
}

Import the custom pipe in pipe-example.componenet.ts file and add the below code.

import { Component } from ‘@angular/core’;
import { custompipePipe } from ‘../custompipe/custompipe.pipe’;

@Component({
selector: ‘app-pipe-example’,
standalone: true,
imports: [custompipePipe],
templateUrl: ‘./pipe-example.component.html’,
styleUrl: ‘./pipe-example.component.css’
})

export class PipeExampleComponent{

monthName:number = 0;
ngOnIt(){

}

getMonthName(event:any){
this.monthName = event.target.value;
}
}

Add the below code in pipe-example.component.html file

<input type=”text” placeholder=”Enter Month Name” (keyup)=”getMonthName($event)” autofocus>
Month Name: {{ monthName | custompipe}}

Input: 12-02-2023

Output: 12-February-2023

 

JavaScript Program To Count The Frequency Of Given Character In String.          Angular Dropdown With Search And Multi Select.

The post Custom Pipe Example In Angular. appeared first on PHPFOREVER.

By

Leave a Reply

X