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:
1.2 Currency Pipe
Formats numbers as currency:
1.3 JSON Pipe
Converts objects into JSON string (useful for debugging):
1.4 Slice Pipe
Extracts a portion of an array or string:
2. Custom Pipes
You can create your own pipes using Angular CLI:
Example: Uppercase First Letter Pipe
Usage:
3. Pure & Impure Pipes
3.1 Pure Pipes
- Default in Angular
- Only re-evaluates when input reference changes
- Fast and efficient
Example:
3.2 Impure Pipes
- Re-evaluates on every change detection cycle
- Useful for dynamic data that changes internally (e.g., arrays, objects)
Example:
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.