Skip to the content.

πŸ“˜ Angular > Pipes

πŸ—οΈ Angular Pipes

Pipes in Angular are used to transform data in templates. They allow you to format, filter, or manipulate data before displaying it in the view. Angular provides several built-in pipes, and you can also create custom pipes to handle specific transformations.


πŸ”„ Built-in Pipes

Angular provides a variety of built-in pipes to handle common data transformations. Here are some of the most commonly used ones:

1. DatePipe

Formats dates in various ways.

<p></p> <!-- Example Output: Monday, April 15, 2025 -->
<p></p> <!-- Example Output: 10:30 AM -->

2. UpperCasePipe and LowerCasePipe

Transforms text to uppercase or lowercase.

<p>hello world</p> <!-- Output: HELLO WORLD -->
<p>HELLO WORLD</p> <!-- Output: hello world -->

3. CurrencyPipe

Formats numbers as currency.

<p>1234.56</p> <!-- Output: $1,234.56 -->
<p>1234.56</p> <!-- Output: €1,234.56 -->

4. DecimalPipe

Formats numbers with decimal places.

<p>1234.5678</p> <!-- Output: 1,234.57 -->

5. PercentPipe

Formats numbers as percentages.

<p>0.25</p> <!-- Output: 25% -->
<p>0.25</p> <!-- Output: 25% -->

6. JsonPipe

Displays objects in JSON format.

<p></p> <!-- Output: {"name":"John","age":30} -->

πŸ› οΈ Creating a Custom Pipe

In addition to built-in pipes, Angular allows you to create custom pipes to handle specific transformations.

πŸ“œ Steps to Create a Pipe

  1. Use the Angular CLI to generate a pipe:
    ng generate pipe my-pipe
    
  2. This command will create the following files:
    • my-pipe.pipe.ts: Contains the pipe logic.
    • my-pipe.pipe.spec.ts: Contains unit tests for the pipe.
  3. Implement the pipe logic in the .pipe.ts file.

πŸ“„ Example: A Custom Reverse Pipe

Here’s an example of a custom pipe that reverses a string:

Pipe File (reverse.pipe.ts):

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

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

Using the Pipe in a Template (app.component.html):

<p>Angular</p> <!-- Output: ralugnA -->

πŸ“œ Key Features of Pipes


πŸ”„ Lifecycle of a Pipe

Pipes are stateless by default, meaning they do not track changes to the input data. However, you can create pure or impure pipes based on your requirements:

Example of an impure pipe:

@Pipe({
  name: 'impureExample',
  pure: false
})
export class ImpureExamplePipe implements PipeTransform {
  transform(value: any): any {
    // Transformation logic
    return value;
  }
}

Understanding Angular pipes is essential for transforming and formatting data in your application. Mastering both built-in and custom pipes will help you create clean and user-friendly interfaces.