1. What is a Pipe?
A pipe takes in data as input and transforms it into a desired output for display in the template. It’s similar to a filter in other frameworks.
Example:
<p>{{ birthday | date:'longDate' }}</p>
Here, the date
pipe transforms a Date
object into a readable format like August 24, 2025
.
2. Built-in Angular Pipes
Angular provides several built-in pipes:
Pipe | Description |
---|---|
date | Formats a date value. |
uppercase | Transforms text to uppercase. |
lowercase | Transforms text to lowercase. |
currency | Formats a number as currency. |
percent | Formats a number as a percentage. |
json | Converts an object to a JSON string. |
Example:
<p>{{ 0.25 | percent }}</p> <!-- Output: 25% -->
<p>{{ 1234.5 | currency:'USD':'symbol' }}</p> <!-- Output: $1,234.50 -->
3. Custom Pipes
You can create your own pipes when the built-in ones are not enough.
Steps:
- Generate a pipe:
ng generate pipe capitalize
- Implement it:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
- Use it in a template:
<p>{{ 'angular' | capitalize }}</p> <!-- Output: Angular -->
4. Chaining Pipes
You can chain multiple pipes together:
<p>{{ 'hello world' | uppercase | slice:0:5 }}</p> <!-- Output: HELLO -->
5. Parameters in Pipes
Some pipes accept arguments:
<p>{{ birthday | date:'shortDate' }}</p>
<p>{{ 0.1234 | percent:'1.2-2' }}</p> <!-- Output: 12.34% -->
Pipes are primarily for display purposes. If you need transformation in logic (e.g., component class), do it there instead.