Pipes
Chapter Objectives
- ✔️PipesLearn how to customize data display in Angular views using pipes.
Angular Pipes
Angular provides a set of built-in pipes to transform data in HTML Templates (views). Pipes are simple functions that accept an input value and return a transformed value. They are used in the view (HTML Template) to format data before displaying it.
Angular pipes are used with the pipe operator |
followed by the pipe name.
You can chain multiple pipes to transform data in the view (HTML Template).
Here are the most commonly used Angular pipes:
uppercase
: transforms a string to uppercaselowercase
: transforms a string to lowercasecurrency
: formats a number as currencydate
: formats a date
You will use the latter to format the task’s createdAt date into a more readable format.
🎓 Instructions
-
Modify the
src/app/task-list.component.html
file.task-list.component.html <table class="table"><thead><tr><th>Name</th><th>Date</th><th>Actions</th></tr></thead><tbody><tr *ngFor="let task of tasks"><td>{{ task.title }}</td><td>{{ task.createdAt | date }}</td><td></td></tr></tbody></table> -
Check the changes in your browser
The task creation date is now displayed in a more user-friendly format.
Alternative (don’t do this)
A common alternative for transforming data in the HTML Template is to use a function. Since interpolation evaluates the JavaScript expression, you can pass it a function that returns a value.
In the following example, we use a function to format the task’s creation date. The function takes the task’s creation date as an argument and returns a formatted date.
<table class="table"> <thead> <tr> <th>Name</th> <th>Date</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let task of tasks"> <td>{{ task.title }}</td>
<td>{{ formatDate(task.createdAt) }}</td> <td></td> </tr> </tbody></table>
export class TaskListComponent { tasks = [ { title: "Task 1", createdAt: new Date() }, { title: "Task 2", createdAt: new Date() }, ];
formatDate(currentDate: Date): string { // Get month, day and year from the Date object const month = currentDate.getMonth() + 1; // getMonth starts at 00 for January, so we add 1 const day = currentDate.getDate(); const year = currentDate.getFullYear(); return month + "/" + day + "/" + year; }}
This will work but not as efficiently as using the date pipe. Angular uses internal change detection to detect changes in the component and update the view (HTML Template). When using a function in the HTML Template, Angular will call the function on every change detection cycle, even if the createdAt date hasn’t changed. Pipes memorize the transformation result and only recalculate it when the input value changes.
✔️ What you’ve learned
Angular pipes allow you to transform data in views (HTML Templates). Although not covered in this introduction, you can also create custom pipes to apply specific transformations to your data.