Crafting Clean and Efficient Angular Apps with Pipes

In Angular, one of the most powerful features for transforming and formatting data within templates is the use of "pipes". Pipes provide a declarative way to process data before it is displayed to the user, enabling developers to apply transformations such as formatting dates, changing text cases, or even filtering data in an efficient and reusable manner.

Understanding how to use pipes effectively is essential for writing clean, maintainable, and modular code in Angular applications. In this article, we will explore what pipes are, the key differences between pipes and functions, how to use built-in pipes, and how to create your own custom pipes to extend Angular’s capabilities. By the end of this guide, you will have a solid understanding of how to incorporate pipes into your Angular projects to streamline data presentation and enhance the user experience.

What is an Angular Pipe?

In Angular, a pipe is a way to transform data before it is displayed in the user interface. Pipes can be used in templates to modify or format data without having to alter the original data.

Pipes are an Angular concept, not a TypeScript (TS) feature. They are a core part of Angular’s template syntax and are used to transform data in the view (template) layer of Angular applications.

Key Points about Pipes in Angular

  • Angular-Specific: Pipes are a built-in feature of the Angular framework designed to be used in Angular templates. They are not a native feature of JavaScript or TypeScript.
  • Purpose: Their primary function is to transform data in the template before it is displayed to the user. This transformation can include formatting dates, numbers, currencies, filtering arrays, or performing more complex data transformations.

Declarative Transformation: Pipes enable declarative transformation of data within the template, meaning that the logic for transforming data is cleanly abstracted away from the component’s TypeScript code.

You may be wondering why we should use Pipes when we can use functions.

Criteria Pipe Function
Purpose Data transformation in the template Business logic and calculations
Use case Formatting, filtering, sorting, etc. Complex or multi-step calculations
Performance Pure pipes are efficient for transforming data only when needed Functions can be less performant when used in templates (requires manual calls)
Reusability Highly reusable across templates Functions are reusable within the component or service
Asynchronous Handling Handles observables and promises with AsyncPipe Requires manual subscription logic or use of 'async' in templates
Complexity Best for simple, declarative transformations Best for complex or dynamic logic
When to use When transforming data for display in the template When performing business logic or side effects that don't belong in the template


Types of Pipes

There are two types of Pipes.

  1. Pure Pipe (Default): A pure pipe will only re-run when its input value changes.
    @Pipe({
      name: 'pureExample',
      pure: true // This is the default value, so you can omit this
    })
    export class PureExamplePipe implements PipeTransform {
      transform(value: any): any {
        console.log('Pure pipe executed');
        return value;
      }
    }

    JavaScript

    Copy

  2. Impure Pipe: An impure pipe will re-run whenever Angular detects a change in the component’s state, even if the input value hasn’t changed.
    @Pipe({
      name: 'impureExample',
      pure: false // Set to false to make it impure
    })
    export class ImpureExamplePipe implements PipeTransform {
      transform(value: any): any {
        console.log('Impure pipe executed');
        return value;
      }
    }

    JavaScript

    Copy

In Angular, you can use in-built pipes or create your own.

In-built pipes

Angular provides some basic pipes that can be used.

It comes from the '@angular/common' package.

Some popular ones that can be helpful are:

CurrencyPipe, DatePipe, DecimalPipe, LowerCasePipe, UpperCasePipe and TitleCasePipe

How to use an in-built pipe?

In your ts file, define your variable. In our example, we will use the variable title.

title = 'app works!';

JavaScript

Copy

In your html, you can use the pipe as follows:

<h1> {{title | uppercase}} </h1>

Markup

Copy

The result is how the string title is displayed:

Chaining in-built pipes

Create your variable in the ts file.

amount = 123456.123456

JavaScript

Copy

In your html file, you can do the following.

<p>{{ amount | currency:'USD' | slice:0:10 }}</p>

Markup

Copy

The result is as per below:

Note. The currency ‘USD’ is added in front because of the currency pipe, and only 10 characters are displayed because of the slide pipe.

Custom pipes

  1. Run the command below to create a pipe file:
    ng generate pipe <<pipe-name>>.

    Bash

    Copy

    For example: ng generate pipe my-custom-pipe. Once executed, the two files below will be created.

    Open the file ‘my-custom-pipe.pipe.ts. You will see the following boilerplate code provided:
    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'myCustomPipe'
    })
    export class MyCustomPipePipe implements PipeTransform {
      transform(value: any, args?: any): any {
        return null;
      }
    }

    JavaScript

    Copy

  2. After the default class, you can create the function for your new pipe. In our case, we will create a pipe that will replace spaces in a hyphen. It is important to add the decorator ‘@Pipe’ before the class so that Angular knows what follows will be a pipe. Also, pass the name of the pipe as a parameter in the ‘@Pipe’ decorator. Also, when creating the class, implement ‘PipeTransform’. The resulting class will be as follows:
    @Pipe({name: 'removeWhiteSpace'})
    export class RemoveWhiteSpacePipe implements PipeTransform {
      transform(value: string): string {
        return value.replace(/\s+/g, '-');
      }
    }

    JavaScript

    Copy

    The resulting class will be as follows (the full code):

    import { Pipe, PipeTransform } from '@angular/core';
    
    
    @Pipe({
      name: 'myCustomPipe'
    })
    export class MyCustomPipePipe implements PipeTransform {
    
    
      transform(value: any, args?: any): any {
        return null;
      }
    }
    
    
    @Pipe({name: 'removeWhiteSpace'})
    export class RemoveWhiteSpacePipe implements PipeTransform {
      transform(value: string): string {
        return value.replace(/\s+/g, '-');
      }
    }

    JavaScript

    Copy

  3. In the ts file of your component, create the variable that will hold the value that will be transformed
    textWithSpaces = 'This is a text with a lot of spaces that will be transformed';

    JavaScript

    Copy

    In the html file of your component, do the following:

    <p>{{ textWithSpaces | removeWhiteSpace }}</p>

    Markup

    Copy

    The result is the following:

Conclusion

Angular pipes are a powerful and efficient way to transform and format data in your application’s templates. By using built-in pipes, you can easily manipulate data types such as strings, dates, and numbers without having to write repetitive logic in your components. Custom pipes offer even more flexibility, allowing you to create reusable, maintainable, and modular transformation logic tailored to your specific needs.

Understanding the distinction between pipes and functions is key to leveraging their full potential. While functions provide a direct way to execute code, pipes offer a declarative approach to handle transformations directly within templates, improving readability and performance.

Whether you're working with Angular’s built-in pipes or creating custom ones, the ability to easily manipulate data in the view layer is a significant advantage in building dynamic and user-friendly applications. By mastering Angular pipes, you can keep your code clean, concise, and aligned with best practices, ultimately leading to more maintainable and scalable applications.

With the knowledge of how to use and create pipes, you’re now equipped to enhance your Angular applications with powerful data transformations, making your development experience more efficient and enjoyable.

Up Next
    Ebook Download
    View all
    test-2
    Read by 1 people
    Download Now!
    Learn
    View all