How to Use Pipe in Angular: Syntax and Examples
In Angular, you use a
pipe to transform data in templates by adding the pipe symbol | followed by the pipe name. Pipes take input data and return transformed output, like formatting dates or uppercase text, directly in your HTML.Syntax
The basic syntax for using a pipe in Angular templates is: {{ value | pipeName:argument }}. Here, value is the data you want to transform, pipeName is the name of the pipe, and argument is an optional parameter to customize the transformation.
html
{{ birthday | date:'fullDate' }}Output
Friday, January 1, 2021
Example
This example shows how to use Angular's built-in date and uppercase pipes to format a date and convert text to uppercase in the template.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-pipe-example', template: ` <p>Original date: {{ birthday }}</p> <p>Formatted date: {{ birthday | date:'fullDate' }}</p> <p>Original text: {{ name }}</p> <p>Uppercase text: {{ name | uppercase }}</p> ` }) export class PipeExampleComponent { birthday = new Date(2021, 0, 1); // January 1, 2021 name = 'angular learner'; }
Output
Original date: Fri Jan 01 2021 00:00:00 GMT...
Formatted date: Friday, January 1, 2021
Original text: angular learner
Uppercase text: ANGULAR LEARNER
Common Pitfalls
Common mistakes when using pipes include:
- Forgetting to import
CommonModulein your module, which provides built-in pipes. - Trying to use pipes in component class code instead of templates.
- Passing wrong or missing arguments to pipes.
- Using pipes for heavy computations, which can hurt performance because pipes run often during change detection.
typescript
Wrong usage in component class: export class MyComponent { transformed = this.name; // ❌ This is invalid to use pipe here } Correct usage in template: <p>{{ name | uppercase }}</p> <!-- ✅ This works -->
Quick Reference
Here is a quick summary of common Angular pipes and their usage:
| Pipe | Description | Example Usage |
|---|---|---|
| date | Formats dates | {{ birthday | date:'shortDate' }} |
| uppercase | Converts text to uppercase | {{ name | uppercase }} |
| lowercase | Converts text to lowercase | {{ name | lowercase }} |
| currency | Formats numbers as currency | {{ price | currency:'USD' }} |
| json | Converts object to JSON string | {{ object | json }} |
Key Takeaways
Use the pipe symbol | in templates to apply a pipe to data.
Pipes transform data for display without changing the original value.
Always use pipes inside templates, not in component TypeScript code.
Import CommonModule to access Angular's built-in pipes.
Avoid heavy computations inside pipes to keep UI responsive.