Loading

Custom Pipes

  • While Angular comes with a variety of built-in pipes for common tasks, custom pipes help developers process data transformations to their special needs. 
  • This allows you to define custom logic for transforming input data into the desired output.

Example: Here we are creating a custom pipe to find a square of a number.

Step 1: Create an Angular project using Angular CLI.

ng new Angular

Step 2: Create a new pipe named ‘custom-pipes’

ng g pipe pipes/custom-pipes

Step 3: Now use the custom pipes in the ‘custom-pipes.pipe.ts’ to design your pipe according to your need.

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

@Pipe({
  name: 'square'
})
export class CustomPipesPipe implements PipeTransform {

  transform(value: number): number {
    return value * value;
  }

}

Step 4: Edit the 'app.component.ts' to define the number.

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: Now define the structure of the HTML for the desired result in  ‘app.component.html’.

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

Step 6: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200