Angular, a powerful JavaScript framework, offers various features to simplify web development. One such feature is Pipes. In this tutorial, we'll dive deep into understanding Pipes, their usage, and real-world applications. Let's get started! 📝
Pipes are a powerful feature in Angular that allow you to transform data in your template. They are used to format, filter, and manipulate data before displaying it to the user.
A pipe is simply a function that you can apply to a property in your component's template. Pipes are chained together using the pipe symbol (|).
{{ property | pipe1 | pipe2 }}Angular provides two types of Pipes:
Built-in Pipes: These are predefined pipes that come with Angular. Examples include DatePipe, DecimalPipe, and JsonPipe.
Custom Pipes: These are pipes you create to perform specific transformations that are not handled by built-in pipes.
Let's explore some built-in pipes and their usage:
The DatePipe is used to format a JavaScript Date object.
import { Component } from '@angular/core';
@Component({
selector: 'app-date-pipe',
template: `
<p>
Today's date is: {{ date | date }}
</p>
`
})
export class DatePipeComponent {
date = new Date();
}In the above example, we're displaying today's date using the DatePipe.
The DecimalPipe is used to format numbers as decimal values.
import { Component } from '@angular/core';
@Component({
selector: 'app-decimal-pipe',
template: `
<p>
Price: {{ price | number: '1.2-2' }}
</p>
`
})
export class DecimalPipeComponent {
price = 1234.5678;
}In the above example, we're formatting the price to display 2 decimal places using the DecimalPipe.
Creating custom pipes allows you to perform specific transformations not handled by built-in pipes.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'uppercase' })
export class UpperCasePipe implements PipeTransform {
transform(value: any): string {
return value ? value.toUpperCase() : value;
}
}In the above example, we've created a custom pipe named uppercase that converts any input to uppercase.
You can chain multiple pipes together to perform multiple transformations on the same data.
import { Component } from '@angular/core';
@Component({
selector: 'app-chain-pipes',
template: `
<p>
Uppercase: {{ name | uppercase }}
</p>
<p>
Fullname: {{ fullName | split:' ' | first: 1 }} {{ fullName | split:' ' | last: 1 }}
</p>
`
})
export class ChainPipesComponent {
name = 'John Doe';
fullName = 'John Doe Smith';
}In the above example, we're first converting the name to uppercase, and then splitting the full name to get the first and last names.
What does the `DatePipe` do in Angular?
By now, you should have a good understanding of Pipes in Angular. They are a powerful feature that allows you to format, filter, and manipulate data in your templates. Happy coding! 🎯