What are pipes in Angular?

Angular, a popular TypeScript-based web application framework, offers powerful tools for data transformation and display. Among these tools, pipes stand out as essential features for manipulating data in templates. Let’s explore Angular pipes, their functionality, and how they can enhance the development process.

Key takeaways:

  • Angular pipes are powerful tools for data transformation in templates.

  • Built-in pipes cover common scenarios like date formatting and number transformations.

  • Custom pipes can be created for specific transformation needs.

  • Pipe chaining allows for multiple transformations in sequence.

  • Understanding the difference between pure and impure pipes is crucial for performance optimization.

Introduction to Angular pipe

Angular pipes provide a sophisticated way to perform the tasks within the templates. They are simple functions that accept an input value and return a transformed output. Pipes make the code structured and clean. They provide a way to declare display-value transformations in the HTML template. Pipes are useful for formatting data such as dates, currency, percentages, and more.

The primary purpose of the pipes is the transformation of an existing value and reusability.

Angular pipe
Angular pipe

How pipes work in Angular

Pipes in Angular work by taking in data as input and producing a formatted output. They are denoted by the pipe symbol (|) in Angular templates. The basic syntax for using a pipe is:

{{ value | pipeName:parameter1:parameter2 }}

Here, value is the input data, pipeName is the name of the pipe, and parameter1 and parameter2 are optional parameters that can be passed to the pipe.

Built-in pipes in Angular

Angular provides several built-in pipes for common data transformations:

Pipe

Description

Example

date

Formats dates according to locale rules

  • {{ date_value | date:'short' }

  • {{ date_value | date:'yyyy-MM-dd' }}

uppercase

Transforms text to uppercase

{{ string_value | uppercase }}

lowercase

Transforms text to lowercase

{{ string_value | lowercase }}

currency

Transforms a number into a currency string

{{ number_value | currency:'USD':'symbol':'1.2-2' }}

number

Transforms a number into a string with decimal points

{{ number_value | number:'1.2-4' }}

percent

Transforms a number into a percentage string

{{ number_value | percent:'2.2-2' }}

json

Converts a value into a JSON-formatted string

{{ object_value | json }}

slice

Creates a subset of an array or string

{{ array_value | slice:1:4 }}

async

Unwraps a value from an asynchronous primitive

{{ observable$ | async }}

titlecase

Transforms text to title case

{{ string_value | titlecase }}

keyvalue

Transforms an Object or Map into an array of key-value pairs

{{item.key}}: {{item.value}}

Let’s look at an example.

Example: Date pipe

Suppose we have a pipe that computes age from a given date input, as shown in the image below.

Angular pipe
Angular pipe

Let’s see the date example in the code as well to get a better understanding.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Code example of a Date pipe in Angular

In the above code:

  • Line 8: We apply the date pipe to the Date object day.

Creating custom pipes

We can create custom pipes to perform specific data transformations. To create a custom pipe:

  1. Use the @Pipe decorator to define the pipe metadata.

  2. Implement the PipeTransform interface.

  3. Override the transform method to define the pipe’s functionality.

Example of a custom pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'exponential'
})
export class ExponentialPipe implements PipeTransform {
transform(value: number, exponent = 1): number {
return Math.pow(value, exponent);
}
}
Creating custom pipes in Angular

Pipe chaining in Angular

Angular allows multiple pipes to be chained together, applying transformations in sequence. This is done by using multiple pipe symbols:

{{ value | pipe1 | pipe2 | pipe3 }}

What if we want the output in uppercase? We can think of it like this:

Pipe chaining in Angular
Pipe chaining in Angular

Let’s see the uppercase date example in the code as well to get a better understanding.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Example of chain pipes in Angular

In the above code:

  • Line 8: We apply the date pipe and uppercase pipe using pipe chaining to the Date object day.

Pure vs. impure pipes

Angular pipes can be categorized as pure or impure:

  • Pure Pipes: Execute only when the input value changes. They are more performant and are the default type.

  • Impure Pipes: Can execute on every change detection cycle. They are less performant but necessary for certain scenarios.

To create an impure pipe, set pure: false in the pipe decorator:

@Pipe({
name: 'myImpurePipe',
pure: false
})
Creating impure pipe in Angular

Best practices for using pipes

Here are some best practices we must follow:

  • Use built-in pipes whenever possible.

  • Create custom pipes for reusable transformations.

  • Prefer pure pipes for better performance.

  • Use pipe chaining judiciously to avoid complexity.

  • Consider using pipes for simple transformations in templates.

Conclusion

Angular pipes are a powerful and essential feature of the Angular framework. It provides tools for data transformation and formatting. From built-in pipes that handle common transformations like date formatting and number manipulation to the flexibility of creating custom pipes for specific needs, Angular’s pipe system proves to be a versatile solution for many data presentation challenges. Remember that effective use of pipes can significantly improve the code’s clarity and maintainability.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is an Angular pipe?

An Angular pipe is a feature that allows you to transform data in your templates. It takes in data as input and returns the transformed data to display. Pipes are denoted by the | symbol in Angular templates.


What is the use of Angular number pipe?

The Angular number pipe (DecimalPipe) is used to format numbers as text. It can be used to control the number of decimal places, add thousand separators, and format numbers according to locale-specific rules. For example: {{ 3.14159 | number:'1.2-2' }} would output 3.14.


How to use Angular pipe in AngularJS?

It’s important to note that Angular (2+) and AngularJS (1.x) are different frameworks. In AngularJS, you would use filters instead of pipes. However, in modern Angular (2+), you use pipes in templates like this: {{ value | pipeName:optionalParameter }}. For example: {{ date | date:'short' }}.


What is the difference between a pipe and a directive in Angular?

While both pipes and directives are used to manipulate data or DOM in Angular, they serve different purposes:

  • Pipes transform output in the template. They are simple functions to use in template expressions to accept an input value and return a transformed value.
  • Directives are used to manipulate the DOM. They can modify the structure of the view or modify attributes in the target elements. Directives come in three types: components, attribute directives, and structural directives. We can also create custom directives.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved