Angular Custom Pipe

Angular provides some default pipes but sometimes we need a pipe that does not exist then we create custom pipe.

How to Create Custom Pipe?

There are some below steps to create a custom pipe. You can create a custom pipe through the Angular CLI command.

Step 1) First create a custom pipe through the angular CLI command.
Syntax:-


ng g pipe pipeName

Example:- Suppose, You create a custom pipe to check number is even or odd.


ng g pipe checkNumberEvenOdd  

When you run the above command, then two files are created.


CREATE src/app/check-number-even-odd.pipe.spec.ts (238 bytes)
CREATE src/app/check-number-even-odd.pipe.ts (241 bytes) 

Step 2) The pipe is automatically included in the module file.


import { CheckNumberEvenOddPipe } from './check-number-even-odd.pipe';
@NgModule({
  declarations: [
    CheckNumberEvenOddPipe
  ]

Step 3) Now, implement the logic that the number is even or odd in the pipe file.


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

@Pipe({
  name: 'checkNumberEvenOdd'
})
export class CheckNumberEvenOddPipe implements PipeTransform {

  transform(value: number): string {
    if(value %2 == 0){
      return 'even';
    }else{
      return 'odd';
    }
  }
}

Step4) Now, define the variable a which is numeric into the app-component.ts file.


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  a : number = 5;
}

Step 5) Now variable passes into the template file like (app-component.html) with checkNumberEvenOdd pipe.


<div align="center">
    <h1>Check Number is Even or Odd</h1>
    <h2>{{a}} is {{a | checkNumberEvenOdd}}</h2>
</div>

Step6) Now run the URL on the browser


http://localhost:4200/

Step7) Now, get the output when passing the number to check it is even or odd.