Saturday, December 1, 2018

Angular Custom Pipes example

Angular provides built-in pipes like date, uppercase, etc to format/transform values. Angular also allows us to create custom pipes for situations where we cannot use the built-in pipes. Custom pipes are created using the @Pipe decorator. Pipes are classes which implement PipeTransform and use the transform() method to provide the transformation logic. The trasform() method takes the input value and pipe parameter values as its arguments.

We can use the ng generate pipe command to create custom pipes. In the following example we will create a simple squareNumber pipe which will take the input value and return the square value of the number. Let us start by create a new custom pipe using the following command.
ng generate pipe squareNumber

This will create a class square-number.pipe.ts, open the file and modify the implementation as follows.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'squareNumber'
})
export class SquareNumberPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return value*value;
  }
}

In this pipe we will not use any parameters hence the args variable will not be used, the value parameter in the value on which the pipe is applied, we just square the value and return it.

To use the pipe in the component include the pipe in the declarations array in the appModule and use it in the component. If we generate the pipe using ng generate pipe command then it will get added to the module automatically. We can use the squareNumber pipe as follows.

Square value: {{2 | squareNumber}}

The output will be

Square value: 4


Search Flipkart Products:
Flipkart.com

No comments: