Exploring Pipes in Angular

Nishu Goel  Print 
26 Sep 2018
28 Sep 2018
Intermediate
519

Transforming and showing the modified data to the user is what pipes are used for, in Angular. Pipes help to apply fine tune to the data and display value transformation to the user. Pipes can also be thought of, as styles which we apply in the HTML template. A pipe takes in some data as input and returns an output based on the output of transform function evaluation.

A simple example of a pipe would be like:

Import {Component } from '@angular/core';
@Component({
 selector: 'app-root',
 template: `<h2>Her birth date is {{ birthdate | date }}</h2>`
 })
 export class AppComponent {
 birthdate = new Date(1996, 5, 5);
 }

In the above example, we have used pipe operator on the birthdate by interpolation. Here, we used the Date pipe function on the right.

Commonly Used Built-in Pipes

There are many more such built-in pipe functions that Angular provides us with. Let us see some of them next.

Slice - used for a list or a string to be sliced.

{{ value_expression | slice : start : end }}

Some of the parameters used with this pipe function are:

  • start (the starting index of the subset to return)

  • end (the ending index of the subset to return)

UpperCase -Transforms text to in upper case format.

 {{ value_expression | uppercase }}

Currency - Transforms a number to a currency string

 {{ value_expression | currency }}

Some of the parameters used with this pipe function are:

  • currencyCode

  • display

  • digitsinfo

  • locale

Json - Converts a value into its JSON-format representation

{{ value_expression | json }}

Chaining of pipes

Angular also provides us the feature to use two or more pipe functions together in a useful combination. This process is known as Chaining of pipes.

{{ birthdate | date | lowercase}}

We can also parameterise pipes using the ":" after the pipe function like:

date: 'fullDate' or {{ num | percent [ : digitsInfo ] }}

Custom Pipe

Another interesting concept with pipes in Angular is that we can create our very own custom pipes and enhance the working of our data. Steps Involved In Creating a Custom Pipe In Angular are

  1. Create a Pipe Class and decorate it with the decorator @Pipe.

  2. Supply a name property to be used as template code name.

  3. Register your Pipe in the module under declarations.

  4. Finally, implement PipeTransform and write transformation logic.

  5. Use your pipe in the HTML using ‘|’, which represents a pipe.

  6. Also, add Custom arguments if you want to.

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

 @Pipe({
 name: 'demo'
 })
 export class DemoPipe{ }

Once we are done creating the Pipe class, we go to app.module.ts and register our pipe.

import { DemoPipe } from './demo.pipe';

 @NgModule({
 declarations: [
 DemoPipe
 ],
 imports: [
 BrowserModule
 ],

To finally put some logic behind the task of our custom pipe, we use PipeTransform.

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

 @Pipe({
 name: 'demo'
 })
 export class DemoPipe implements PipeTransform{
 transform(n: number) {}
 }

So, to maintain the required standard structure, we use transform() method inside PipeTransform.Now, our motive is to convert some random number to a readable format of kilograms, and to do that, we put logic inside transform() as follows

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

 @Pipe({
 name: 'demo'
 })
 export class DemoPipe implements PipeTransform{
 transform() : string {
 return (n *1000).toFixed(2) + 'Kg';
 }
 }

Now to use it in the HTML,

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

To add a custom argument to your output, simply add the capability of extension to the Transform() method as follows.

import { Pipe, PipeTransform } from '@angular/core';
 
 @Pipe({
 name: 'demo'
 })
 export class DemoPipe implements PipeTransform{
 transform(n: number, extension: string = 'Kilograms') {
 return (n * 1000).toFixed(2) + extension;
 }
 }

This is how you can create a custom pipe for your own.

Pipe Categories

Pipes, in general have two categories

  • Pure (all pipes by default are pure)

  • Impure pipes

Pure pipes are executed when there is a change to the primitive input value or the object reference is changed, whereas Impure pipes are executed during every component Change Detection cycle. (Change Detection is a vast concept in itself which is out of the scope of this article). Some interesting examples of Impure Pipes are:

  • AsyncPipe (used with Observables)

  • CachingPipe (used to make HTTP request)

Summary

This blog post explains how using a pipe, we can transform data and display it to the user. It also discussed the use of built-in pipes in Angular like DatePipe, PercentPipe etc. and how we can create and use Custom pipes to enhance the working of our Angular projects with the code examples. By the end of the article, some light was put on Pure and Impure Pipes and their examples.

Crack Your Technical Interview

 
Join Our Hands-on Training Programs
+