Menu

What is Pipe in Angular and Transform Data Using Pipes?

What are pipes in Angular?

Pipe in Angular and transform

Angular gives few useful filters called Pipes. These make them very easy to format or transform the data value even as per our requirements. A Pipe is used with a Pipe(|) character, it takes an input and returns a desired formatted output.

It takes strings, integers, arrays, and date as input split with | to be converted in the format as required and displays the identical within the browser. Pipes are chainable. As expressed data transformers, pipes are hardly minor. Pipe transforms template data directly.

Types of pipes in Angular 

Angular is considered among the most popular frameworks for web development. Talking about the types of pipes in Angular, it has two and they are –

  • Pure pipe
  • Impure pipe

Pure pipe: 

  • Everything you’ve got been so far has been a pure pipe.
  • Pure: true is prepared by default @pipe decorator’s metadata.
  • Pure pipes update automatically whenever the value of their derived input changes.
  • The pipe will re-execute to consume new output upon detectable changes in the input value. 

Impure pipe:  

  • Impure pipe update automatically whenever a change detection cycle occurs.
  • In the case of an impure pipe, it’ll update irrespective of whether there are detectable changes or not.
  • Impure pipes usually consume many resources and are generally ill-advised.
  • That said, they operate more like an escape scuttle.
  • If you ever need a detection-sensitive pipe, toggle pure: false within the @pipe decorator’s metadata.

Let’s see an easy example demo of Pipes:

            In the following example, we want to display the text given to uppercase and lowercase.

            This will be completed using pipes as follows-

            In thepipedemo.component.ts file, we’ve to define details variable-

                       

import { Component,    OnInit } from ‘@angular/core’;

 

@Component({

  selector: ‘app-pipedemo’,

  templateUrl: ‘./pipedemo.component.html’,

  styleUrls: [‘./pipedemo.component.css’]

})

export class PipedemoComponent implements OnInit {

details=”Angular pipes Demo!”;

  constructor() { }

ngOnInit(): void {

  }

}

                                                                           [pipedemo.component.ts]

The line of code goes below the pipedemo.component.html file.

<b>{{details|uppercase}}</b>

<br>

<br>

<b>{{details|lowercase}}</b>

                                                                           [pipedemo.component.html]

And following is that the output of the above example.

           Output

                                    [output of pipe demo]

Built-in pipes in angular

Angular supplies some built-in pipes for particular data transformations. The pipes are listed below-

  • LowercasePipe: transforms text to all lower case.
  • UppercasePipe: transforms text to all upper case.
  • DatePipe:    Formats a date value in step with locale value.
  • CurrencyPipe: transforms a number to a currency string, formatted in keeping with locale rules.
  • JsonPipe:    transforms a JSON value in string format.
  • PercentPipe: transforms a number to a percentage string, formatted consistent with locale rules.
  • DecimalPipe: transforms a number into a string with a decimal point, formatted consistent with locale rules.
  • SlicePipe: creates a new string that contains a subset of the elements.

            In the following example, we apply the built-in pipes demo.

            In thepipedemo.component.ts file, we’ve got to defined variables-

import { Component, OnInit } from ‘@angular/core’;

 

@Component({

  selector: ‘app-pipedemo’,

  templateUrl: ‘./pipedemo.component.html’,

  styleUrls: [‘./pipedemo.component.css’]

})

export class PipedemoComponent implements OnInit {

details=”Angular pipes Demo!”;

todaydate=new Date();

jsonvalue={name:”Abcd”,age:22,city:{c1:’ahemdabad’,c2:’mumbai’}};

days=[“sunday”,”monday”,”tuesday”,”wednesday”,”thursday”,”friday”,”saturday”];

constructor() { }

ngOnInit(): void {

  }

}

                                                                                                      [pipedemo.component.ts]

The following line of code goes below the pipedemo.component.html file.

<div style=”width:100%;”>

<div style=”width: 40%;float: left;

border: 1px solid black;”>

        <h2>UpperCase</h2>

        <b>{{details|uppercase}}</b>

        <br>

        <h2>LowerCase</h2>

        <b>{{details|lowercase}}</b>

        <br>

        <h2>Currency pipe</h2>

        <b>{{9238.46|currency:”USD”:true}}</b>

        <br>

        <h2>Date Pipe</h2>

        <b>{{todaydate|date:’d/M/Y’}}</b><br>

        <b>{{todaydate|date:’shortTime’}}</b>

        <br>

        <h2>Decimal pipe</h2>

        <b>{{121.434567|number:’3.4-4′}}</b>

        <br>

        <h2>json pipe</h2>

        <b>{{jsonvalue|json}}</b>

        <h2>Percent Pipe</h2>

        <b>{{00.6589|percent}}</b>

        <h2>slice pipe</h2>

        <b>{{days|slice:3:6}}</b>

 

      </div>

 </div>

                                                                        [pipedemo.component.html]

And here is that the output of the above code.

pipedemo component output

How to create a custom pipe in angular? 

To create a custom pipe, we’ve created a new component name as a custom pipe.

Here, we wish to make a custom pipe.

Steps of creating a custom pipe in angular are – 

  1. Now first we create a pipe class and then decorate it with the decorator @pipe.
  2. Supply a name property to be used as a template code name.
  3. Register your pipe in the module under-declarations.
  4. Finally, implement pipe transform and write transformation logic.
  5. You can use pipe in the HTML using ‘|’, which represents a pipe.
  6. Also, if you would like to add custom arguments in these you’ll be able to.

import { Pipe } from “@angular/core”;

 

@Pipe({

  name: ‘demo’

})

export class CustompipeComponent {

 constructor() { }

 ngOnInit(): void {

  }

}

                                                                                          [custompipe.component.ts]

In the following line of code goes the custompipe.component.html file.

<div>

    <p>{{demo.name}}</p>

    <p>{{demo.n|demo}}</p>

</div>

                                                                        [custompipe.component.html]

Now you add a custom argument to your output, and easily add the capability of extension to the transform() method as follows.

The following line of code goes below the custompipe.component.ts file.

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

 

@Pipe({

  name: ‘demo’

})

export class CustompipeComponent implements PipeTransform{

  

transform(n:number,extension:string=’ABCD’){

   return(n*1000).toFixed(2)+extension;

 }

  constructor() { }

  ngOnInit(): void {

  }

}

                                                                                                         [custompipe.component.ts]

We can also add multiple arguments which might be split using ‘:’.

Transform data using pipes

  • Use optional arguments to fine-tune a pipe’s output.
  • Let’s some good examples of transforming a date using a pipe.
  • The tabs in the following example demonstrate toggling between different formats(‘shortDate’ and ‘fullDate’).
  • The datepipedemo.component.ts component binds the pipe’s format parameter to the format property in the template section and adds a button for a click event to the component’s showToggle() method.
  • The datepipedemo.component.ts component’s showToggle() method toggles the component’s format property between a short form (‘shortDate’) and a longer form (‘fullDate’).

The line of code goes below the datepipe.component.ts file.

import { Component, OnInit } from ‘@angular/core’;

 

@Component({

  selector: ‘app-datepipedemo’,

  templateUrl: ‘./datepipedemo.component.html’,

  styleUrls: [‘./datepipedemo.component.css’]

})

export class DatepipedemoComponent implements OnInit {

  birthday = new Date(1988, 3, 15);

  toggle = true;

  get format() 

    { 

      return this.toggle ? ‘shortDate’ : ‘fullDate’; 

    }

  showToggle() { 

    this.toggle = !this.toggle; 

  }

  constructor() { }

 ngOnInit(): void {

  }

}

                                                                                          [datepipe.component.ts]

The line of code goes below the datepipe.component.html file.

<p>The xyz’s birthday is {{ birthday | date:format }}</p>

<button (click)=”showToggle()”>show Format</button>

                                                                        [datepipe.component.html]

And following is that the output of the above example.

datepipe component output

                        [output:1 without clicking the button]

After clicking the show Format button…

show Format button

                                    [output:2 after clicking the button]

 

Conclusion

This blog covers the concept of pipes. Pipes are fabulously helpful behind the scope and are a good example in situations where data must go through small transformations. Here, we use the concept of pipes to transform threads, currency amounts, dates, and other display data. Pipes are simple functions you can use in template expressions to receive an input value and go back to a transformed value.

Leave a Reply

Your email address will not be published. Required fields are marked *