Browse Articles

Exploring Pipes in Angular

 Print   6 min read  
23 Jul 2022
Intermediate
8.01K Views

Transforming and showing the modified data to the user is what pipes are used for, in Angular. Pipes help to apply to fine-tune the data and display value transformation to the user. Pipes can also be thought of, as styles that 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.

Angular pipes definition and its usage is pretty straightforward and realizing that they can be very useful as the name suggests. Angular comes with tons of helpful built-in pipes that are ready for use and also allow us to create our customized pipes, and we are going to dive into it briefly in this.

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 a pipe operator on the birthdate by interpolation. Here, we used the Date pipe function on the right.

Commonly Used Built-in Pipes

Angular provides various built-in pipes which can be used typically for the data transformations, including currency, decimal, upper and lower case along with transformations for internationalization, which use locale information to format data. The following are commonly used built-in pipes for data formatting: DatePipe: Formats a date value according to locale rules.

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 }}

Percent - Percent pipe is used to transform the percent number into the well-formatted string as given below

{{ 0.295 | percent }}

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 the Chaining of pipes.

{{ birthdate | date | lowercase}}

We can also parameterize 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 a 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 the 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 requests)

Summary

Pipes is one of the most popular features that any developer can use to do some quick changes as per the business requirement because Pipes are very handy that it can get the work done with the minimal setup yet effective transformation, for that we can consume all the given pipes and not so then create the customized pipe to get started.

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.

| Read More: Angular Interview Question and Answer

Learn to Crack Your Technical Interview

Accept cookies & close this