Angular Pipes & custom pipes
Master Angular Pipes: Introducing Data Using Built-in and Custom Pipes
When you finish, you will:
✅ Have an understanding of how pipes categorize data handling.
✅ Be able to use Angular's built-in pipes for date and money as well.
✅ Know how easy it is to fashion a custom pipe.
✅ Avoid common mistakes and follow best practices.
Turn dirty data into something that users love!
The Importance of Angular Pipes
Pipes offer a kind of form object that you can put in a template in front of the user directly. They're essential because:
- Clean Code: Keep formatting out of containers.
- Usability: Mix and match types.
- Human-Friendly Interface: Style dates, currencies, and other text in a way that people can comprehend.
What Are Angular Pipes?
Pipes are functions that take in a variable and return a new value after processing. In a template, they are attached to the variable by the vertical line (|) followed by the pipe name:
{{ rawData | pipeName }}
Built-in Pipes: The Data Swiss Army Knife
Angular provides more than 20 convenient pipes. Here is a selection of common ones:
Pipe | Example | |
---|---|---|
DatePipe | `{{ today | | date:'short' }}` |
CurrencyPipe | `{{ price | | currency:'USD' }}` |
UpperCasePipe | `{{ 'hello' | | uppercase }}` |
JsonPipe | `{{ user | | json }}` |
Creating a Custom Pipe in 4 Steps
We want to create TruncatePipe for when we have long text and need to present it with an ellipsis (e.g., "Lorem ipsum...").
Step 1: Generate the Pipe
ng generate pipe truncate
This creates truncate.pipe.ts and a test file.
Step 2: Define the Logic
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, maxLength: number = 50, ellipsis: string = '...'): string {
if (!value) return '';
return value.length > maxLength ? value.slice(0, maxLength) + ellipsis : value;
}
}
Step 3: Declare the Pipe
Add to your module's declarations (or use standalone: true in Angular 15+):
@NgModule({
declarations: [TruncatePipe],
})
export class AppModule {}
Step 4: Use It in a Template
{{ longText | truncate: 30 : "…" }}
Input: "With Angular pipes, data formatting is a piece of cake!"
Output: "With Angular pipes, data form…"
5 Real-World Custom Pipe Ideas
- Highlight Matches in Search Results: Develop a pipe that can transparently highlight matching text in a search.
- File Size Formatter: Change bytes into KB, MB, or GB.
- Emoji Converter: Switch :smile: into 😃.
- Password Mask: Cover raw text with ••••• so a user can’t read it.
- Temperature Converter: Convert between °C and °F.
Angular Pipe Best Practices
- Keep Pipes Pure: Avoid side effects (unless you really need to use impure pipes).
- Parameterize: Design pipes so they can be customized through input (like adding maxLength to TruncatePipe).
- Optimize Performance: Pure pipes aren't unexpectedly invoked.
- Test Thoroughly: Edge cases should be covered by Angular's own testing procedure.
- Use with Async Data: Pair the async pipe with Observables/Promises
{{ data$ | async | uppercase }}
Common Pitfalls to Avoid
🚫 Overuse of Impure Pipes: They’re called with each template change detection, which can hurt performance.
🚫 Ignoring Localization: For more information, link CurrencyPipe with global settings for your app.
🚫 Leaving out Error Handling: Check that custom pipes are not null/undefined.
Conclusion: Add Pipes to Your Angular Apps
Pipes are Angular's secret weapon for clear, reusable data formatting. Whether you're formatting dates or creating custom logic, your users will thank you when they find clean templates.
Your Next Moves:
- Replace manual output with Angular's built-in pipes in your project.
- Create a custom pipe for a unique requirement in your project.
- Pass this guide to your team!
Ask us any further questions by adding a comment below.
External Links: