Mastering Angular Pipes: From Basics to Advanced Techniques

As an Angular developer, mastering the use of Angular Pipes can significantly enhance your ability to manage and transform data efficiently within your applications. Angular Pipes offers a clean, declarative approach to data transformation directly in your templates, making your code more readable and maintainable.

In this comprehensive guide, we’ll explore built-in Angular Pipes, delve into creating custom Angular Pipes, and differentiate between pure and impure Angular Pipes to optimize your application’s performance.

What are Angular Pipes?

Angular Pipes are functions that transform data before it is displayed in the view. They take in data as input and transform it into a desired format using simple expressions. This approach ensures that the data presentation is consistent and the logic is encapsulated within reusable components.

Related read: Creating Reusable Angular Components with the NgTemplateOutlet Directive

Built-in Pipes in Angular

Angular includes several built-in Angular Pipes that simplify common data transformations. Here are a few that are frequently utilized:

1. DatePipe

Formats a date value according to locale rules.

<p>{{ today | date:'fullDate' }}</p>

Output: Displays the current date in a full date format, e.g., “Monday, June 15, 2024”.

2. UpperCasePipe & LowerCasePipe

Transforms a string to uppercase/lowercase.

Uppercase : <p>{{ 'hello world' | uppercase }}</p>
Uppercase : <p>{{ ‘HELLO WORLD' | lowercase}}</p>

Output: Uppercase: “HELLO WORLD”, lowercase: “hello world”.

3. CurrencyPipe

Formats a number as currency.

<p>{{ price | currency:'USD' }}</p>

Output: “$1,234.56” (assuming the price is 1234.56).

4. DecimalPipe

Formats a number with specified decimal points.

<p>{{ pi | number:'1.2-2' }}</p>

Output: “3.14” (assuming the pi is 3.14159265359).

5. PercentPipe

Transforms a number into a percentage.

<p>{{ ratio | percent }}</p>

Output: “85%” (assuming the ratio is 0.85)

6. JsonPipe

Converts an object to a JSON string.

<pre>{{ data | json }}</pre>

Output:

{
"name": "Angular",
"version": "11"
}

(assuming data is an object { “name”: “Angular”, “version”: “11”} ).

Boost Your App's Performance with Expert Pipe Implementation. Hire Our Developers Now!

Pure vs. Impure Pipes

Understanding the difference between pure and impure Angular Pipes is crucial for optimizing your Angular applications.

Pure Pipes

Pure pipes are stateless and their output depends solely on the input parameters. They are recalculated only when the input reference changes, making them efficient for most use cases.

When to Use Pure Pipes

  • When the data is immutable.
  • When the transformation logic is simple and based only on input value changes.
  • To improve performance by minimizing recalculations.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'uppercase',
  pure: true
})
export class UpperCasePipe implements PipeTransform {
  transform(value: string): string {
    return value.toUpperCase();
  }
}

Impure Pipes

Impure pipes are stateful and can have side effects. They are called on every change detection cycle, making them suitable for scenarios where the data can change frequently.

When to Use Impure Pipes

  • When the data is mutable and changes frequently.
  • When the transformation logic depends on more than just the input parameters.
  • For operations that involve filtering or sorting dynamically changing data.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items || !searchText) {
      return items;
    }
    return items.filter(item => item.name.includes(searchText));
  }
}

Creating Custom Pipes

Custom pipes allow you to encapsulate complex logic in a reusable component. Here’s a step-by-step guide to creating a custom pipe that reverses a string:

Step 1: Generate a Pipe

Use Angular CLI to generate a new pipe:

ng generate pipe reverse

Step 2: Implement the Pipe Logic

Edit the reverse.pipe.ts file:

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

@Pipe({
       name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
     return value.split('').reverse().join('');
  }
}

Step 3: Use the Custom Pipe in a Template

Add the custom pipe to your template:

<p>Reversed text: {{ 'angular' | reverse }}</p>

Advanced Angular Pipe Techniques

Chaining Pipes

You can combine multiple pipes in sequence to achieve complex data transformations.

<p>{{ birthday | date:'fullDate' | uppercase }}</p>

Parameterizing Pipes

Pass parameters to pipes for dynamic transformations.

<p>{{ price | currency:'USD' }}</p>

Using AsyncPipe

Handle asynchronous data streams with ‘AsyncPipe’.

<p>{{ observableData$ | async }}</p>
coma

Conclusion

Angular pipes are a powerful feature that can simplify data transformation and presentation in your applications. By mastering built-in pipes, understanding the distinction between pure and impure pipes, and creating custom pipes, you can significantly enhance your development workflow. Experiment with advanced techniques like chaining and parameterizing Angular Pipes to make your applications more efficient and maintainable.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?