Angular Pipes

  • In Angular 1 it is called as filters
  • From Angular 2 it is called as pipes
  • We have many bult-in pipes. We can also create our own pipes
  • It is used to convert the format and display in browser.
  • It uses “|” character to perform this operation.
  • Example, if we want a value to be displayed in uppercase or lowercase or with fixed decimals etc.
  • It is declared as @directive
{{ Welcome to Angular 7 | lowercase}}	
Below are a few commonly used built in pipes.
  • Lowercase
  • Uppercase
  • Date
  • Currency
  • Slicepipe
  • Decimalpipe
  • Jsonpipe
  • Percentpipe

You can use these option as below in your app.component.html

      <h1>Uppercase Pipe</h1>
      <b>{{title | uppercase}}</b>
      <br/>
      
      <h1>Lowercase Pipe</h1> 
      <b>{{title | lowercase}}</b> 
      <h1>Currency Pipe</h1> 
      <b>{{6589.23 | currency:"USD"}}</b>
      <br/> 
      
      <b>{{6589.23 | currency:"USD":true}}</b> 
      // Boolean true is used to get the sign of the currency. 
      <h1>Date pipe</h1>
      <b>{{todaydate | date:'d/M/y'}}</b>
      <br/> 
      
      <b>{{todaydate | date:'shortTime'}}</b>
      <h1>Decimal Pipe</h1>
      <b>{{ 454.78787814 | number: '3.4-4' }}</b>


<h1>Json Pipe</h1>
      <b>{{ jsonval | json }}</b>
      <h1>Percent Pipe</h1> 
      <b>{{00.54565 | percent}}</b> 
      <h1>Slice Pipe</h1> 
      <b>{{months | slice:2:6}}</b> 
      // here 2 and 6 refers to the start and the end index

Custom Pipe:

To create a new custom pipe, we need to create a new ts file.

To create a custom pipe, we need to import pipe and pipe transform from angular core. We need to add @Pipe directive and add our name. The same name will be used for transformation in html.

We can also do the same using ng cli as below

ng g pipe square
Below screenshot show the output of the command.

custom-pipe

We can see square.pipe.ts is created and added to app.module.ts

Square.pipe.ts is created with below code
import { Pipe, PipeTransform } from '@angular/core';

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

  transform(value: unknown, ...args: unknown[]): unknown {
    return null;
  }

}

We can modify the transform function as below to show the square of a value.

transform(val : number) : number {
    return val * val;
 }
We can use this pipe in app.component.html as below
 <h1 > {{  2 | square}} </h1>
 <h1> {{  6 | square}} </h1>
Below SS show the output on the browser

custom-pipe-output

Subscribe Now