Introduction
Pipes are a fundamental feature in Angular that allows you to transform data before displaying it in the user interface. They provide a concise and reusable way to format and modify data, ensuring a smooth user experience.
1. Built-in Pipes
Angular comes with several built-in pipes that cover various data transformation scenarios. Some commonly used built-in pipes include:
- DatePipe: Used for formatting dates.
- UpperCasePipe: Converts text to uppercase.
- LowerCasePipe: Converts text to lowercase.
- CurrencyPipe: Formats currency values.
- DecimalPipe: Formats numbers as decimals.
- PercentPipe: Formats numbers as percentages.
2. Creating Custom Pipes
You can also create your own custom pipes to cater to specific data transformation needs. To create a custom pipe, you need to implement the PipeTransform
interface and provide a transform
method. Here's an example of a custom pipe that adds a prefix to a string:
typescriptimport { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'prefix' })
export class PrefixPipe implements PipeTransform {
transform(value: string, prefixText: string): string {
return prefixText + value;
}
}
3. Using Pipes
To use a pipe in your Angular template, you can apply it to an expression using the pipe operator (|
). For example, using the custom PrefixPipe
:
html<p>{{ 'World' | prefix: 'Hello ' }}</p>
<!-- Output: Hello World -->
You can also chain multiple pipes together to apply multiple transformations:
html<p>{{ currentDate | date: 'dd/MM/yyyy' | uppercase }}</p>
<!-- Assuming currentDate is a Date object and the current date is 30th July 2023 -->
<!-- Output: 30/07/2023 -->
4. Practical Example: Formatting Numbers with DecimalPipe
Suppose you have a list of numbers and want to display them with two decimal places. First, import the DecimalPipe
and add it to the providers
array in your component or module:
typescriptimport { Component } from '@angular/core';
import { DecimalPipe } from '@angular/common';
@Component({
selector: 'app-number-list',
template: `
<ul>
<li *ngFor="let number of numbers">{{ number | number:'2.2-2' }}</li>
</ul>
`,
providers: [DecimalPipe]
})
export class NumberListComponent {
numbers: number[] = [3.1415, 42.857, 7.77, 123.4];
}
The number:'2.2-2'
pipe expression formats the number with two decimal places and displays at least two digits before the decimal point.
Conclusion
Pipes are powerful tools in Angular for transforming data, and they can significantly enhance the user experience by presenting data in a more readable and organized manner. Whether using built-in pipes or creating custom ones, you have the flexibility to handle data transformations efficiently.
0 Comments