What are Pipes in Angular - Pure & Impure Pipe in Angular (With Example

What are Pipes in Angular - Pure & Impure Pipe in Angular (With Example

21 Aug 2024
Intermediate
12.2K Views
12 min read
Learn with an interactive course and practical hands-on labs

Self-Paced Angular Certification Course

Exploring Pipes in Angular: An Overview

An effective tool in Angular for changing data inside templates is pipes. They provide a practical means of organizing, screening, and modifying data before its presentation to consumers. Explore online resources such as Angular Tutorials and Angular Certification Courses for more in-depth information.

Exploring Pipes in Angular: An Overview

What are Pipes in Angular?

Pipes are functions in Angular that take in input data and provide altered output data. They can be used to filter and sort arrays and format dates, integers, strings, and other kinds of data within template expressions. Pipes improve the presentation layer of Angular applications and make data handling easier.

Pipes in Angular

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.

 pipe operator on the birthdate by interpolation

Commonly Used Built-in Pipes

Angular provides various built-in pipes that can be used typically for 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:

  1. Currency Pipe
  2. Date Pipe
  3. Json Pipe
  4. LowerCase Pipe
  5. UpperCase Pipe
  6. PercentPipe
  7. SlicePipe
  8. TitleCasePipe
  9. AsyncPipe

Let us see some of them next.

1. 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)

2. UpperCase -Transforms text to upper case format.

 {{ value_expression | uppercase }}

3. 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

4. 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 ] }}

Creating Custom Pipes

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.

Types of pipes in Angular

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 angular 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)

Best practices for using pipes

  • Make use of built-in pipes: To reduce overhead, make use of Angular's optimized built-in pipes, such as DatePipe, CurrencyPipe, and DecimalPipe.
  • Avoid excessive chaining: Limit pipe chaining to avoid performance issues, particularly when working with big datasets. Instead, think about data preprocessing or bespoke pipes.
  • Performance considerations: Minimise pipe calls and steer clear of complex computations inside them.
  • Maintain simple pipes: Keep pipelines simple and concentrate on single transformations to make debugging and maintenance easier.
  • Pure pipes are preferred: To improve performance, use pure pipes and only call them when the input changes.
  • Recognize the different data types: To guarantee proper behavior, be aware of the data types that various pipes demand.
  • Conduct a comprehensive test: Perform thorough testing, including component and unit testing, on custom pipelines to ensure functioning and integration.

Read More:

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.

FAQs

The pipe transform method's primary function is to change one value into another. The value may simultaneously be an integer, string, object, or array, among other data types. To carry out the required action, you can design your custom pipes in the angular cli.

Pipes allow us to customize how objects in component templates are rendered. A few built-in pipes in Angular allow us to render string and integer data in a format that is specific to a given locale. Additionally, pipes can be used to retrieve values returned from promises and observables as well as to obtain a slice of arrays or strings.

As demonstrated in the code example below, use the pipe operator (|) in a template expression to apply a pipe. The pipe operator (|) transfers the birthday value of the component to the DatePipe, whose pipe name is the date. The date is rendered by the pipe as April 15, 1988, in the default format. Examine the component class.

Take our Angular skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Nishu Goel (Angular developer, Author, and Speaker)

Nishu is an Angular developer, Author, and Speaker. She is working as a Developer at IBM with her major interest in technologies and frameworks like Angular, JavaScript, CSS. She also works towards achieving the SDGs by United Nations, by applying technology towards better livelihood. Her hobbies include blogging about the latest technologies and creating a better ecosystem for students.
Accept cookies & close this