What is Pipe and How to use Custom Pipe

nitish96
Nitish Sharma
Published on: December 5, 2024
Updated on: December 30, 2024
What is Pipe and How to use Custom Pipe blog

Pipes are a powerful feature in Angular that allows developers to transform data directly in the template. They are an easy way to format and transform data displayed to the user without changing the underlying data model.

What are Pipes?

A Pipe in Angular is a class that implements the PipeTransform interface and provides a transformation function. The Pipe can then be used in templates with the Pipe ( | ) character to process data before displaying it.

<p>{{today | date:'dd-MM-yyyy'}} </p>

Built-in Pipes in Angular

               Pipe

Purpose

date

Formats date/time

currency

Formats numbers as currency

uppercase

Converts text to uppercase

lowercase

Converts text to lowercase

json

Formats objects as JSON

async

Handles asynchronous data

Slice

Extracts a portion of a string/array

 

Create a Custom Pipe

create a custom pipe to convert a given time into specific format: hh:mm aa

Generate a Pipe

You can generate a pipe using Angular CLI:

ng generate pipe custom-time-format

Implement the Pipe Logic

Add change in generated Pipe file: custom-time-format.pipe.ts

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

@Pipe({
  name: 'customTimeFormat'
})
export class CustomTimeFormatPipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return '';
    
    const [hours, minutes] = value.split(':').map(Number);
    const period = hours >= 12 ? 'PM' : 'AM';
    const formattedHours = hours % 12 || 12;
    
    return `${formattedHours}:${minutes.toString().padStart(2, '0')} ${period}`;
  }
}

Use the Pipe in a Component Template

Add the pipe to the declarations array of your module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CustomTimeFormatPipe } from './custom-time-format.pipe';

@NgModule({
  declarations: [
    AppComponent,
    CustomTimeFormatPipe
  ],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }


Then use the pipe in a template:

<p>Original Time: 14:30</p>
<p>Formatted Time: {{ '14:30' | customTimeFormat }}</p>

<!-- output:
Original Time: 14:30
Formatted Time: 2:30 PM -->

Conclusion:

Pipes are an excellent way to simplify data transformations in Angular templates. While Angular provides several built-in pipes, custom pipes allow you to meet unique requirements and make your application more robust and user-friendly

If you have any questions or concerns, please feel free to let us know. Our team will connect with you shortly to assist.

Comments

Login to leave a comment.

Build Software Application with Impact Hive