Angular Pipes
Pipes in Angular transform data in the template without changing the underlying data in the component. They make templates cleaner and more readable. There are built-in pipes and custom pipes. Pipes can also be pure or impure based on how they detect changes.
1. Built-in Pipes
Angular provides several built-in pipes to format data:
1.1 Date Pipe
Formats dates:
<p>{{ today | date }}</p> <!-- default format -->
<p>{{ today | date:'fullDate' }}</p> <!-- Friday, December 1, 2025 -->
<p>{{ today | date:'shortTime' }}</p> <!-- 10:45 AM -->
today = new Date();
1.2 Currency Pipe
Formats numbers as currency:
<p>{{ amount | currency }}</p> <!-- $1,500.00 -->
<p>{{ amount | currency:'INR' }}</p> <!-- ₹1,500.00 -->
amount = 1500;
1.3 JSON Pipe
Converts objects into JSON string (useful for debugging):
<p>{{ user | json }}</p>
user = { name: 'Chinmaya', age: 30 };
1.4 Slice Pipe
Extracts a portion of an array or string:
<p>{{ name | slice:0:4 }}</p> <!-- 'Chin' -->
name = 'Chinmaya';
2. Custom Pipes
You can create your own pipes using Angular CLI:
ng generate pipe filter
# or
ng g p filter
Example: Uppercase First Letter Pipe
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);
}
}
Usage:
<p>{{ 'angular' | capitalize }}</p> <!-- Angular -->
3. Pure & Impure Pipes
3.1 Pure Pipes
- Default in Angular
- Only re-evaluates when input reference changes
- Fast and efficient
Example:
@Pipe({ name: 'purePipe', pure: true })
3.2 Impure Pipes
- Re-evaluates on every change detection cycle
- Useful for dynamic data that changes internally (e.g., arrays, objects)
Example:
@Pipe({ name: 'impurePipe', pure: false })
Tip: Use impure pipes sparingly as they can affect performance.
4. Best Practices
- Use built-in pipes whenever possible.
- For repeated transformations, create custom reusable pipes.
- Prefer pure pipes to keep the app performant.
- Avoid impure pipes for large datasets; consider using async pipe with Observables instead.
- Keep pipe logic simple; heavy processing should be in the component or service.
Summary
- Pipes transform data in templates without changing the original data.
- Built-in pipes:
date,currency,json,slice. - Custom pipes allow reusable transformations.
- Pure pipes execute only when inputs change; impure pipes execute every change detection cycle.
- Use pipes for cleaner templates and efficient data display.