Loading
Angular already gives you useful built-in pipes to format data, like

  • Date formatting
  • Uppercase/lowercase text
  • Currency formatting
But sometimes, you need to display data in a special way that the built-in pipes don’t cover.
This is where custom pipes come in

Custom pipes let you

  • Write your own logic
  • Transform data exactly the way you want
  • Keep your templates clean and reusable



Example: Creating a Custom Pipe to Square a Number


Step 1: Create a New Angular Project

ng new Angular



Step 2: Generate a Custom Pipe

ng g pipe pipes/custom-pipes

This creates two files

  • custom-pipes.pipe.ts
  • custom-pipes.pipe.spec.ts (for testing)



Step 3: Add Logic to Your Custom Pipe

Edit custom-pipes.pipe.ts

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

@Pipe({
  name: 'square'
})
export class CustomPipesPipe implements PipeTransform {
  transform(value: number): number {
    return value * value;
  }
}

Here is what this does:

  • @Pipe({ name: 'square' }) - The pipe will be used as | square in templates
  • transform method - Takes the input number and returns its square



Step 4: Add Data to Use the Pipe

Edit app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular';
  originalNumber = 5;
}



Step 5: Use the Custom Pipe in Your Template

Edit app.component.html

<h1>Custom Pipes Example</h1>
<div>
    Original Number: {{ originalNumber }}
</div>
<div>
    Squared Number: {{ originalNumber | square }}
</div>

| square applies the custom pipe you created.



Step 6: Run Your App

ng serve


Open your browser at: http://localhost:4200


You will see

Original Number: 5
Squared Number: 25