Angular offers a robust feature called pipes, which are essential for transforming data right within your templates. With pipes, you can format, filter, and adjust your data before it is presented to the user.
Understanding Pipes in Angular:
Pipes are functions that take an input value and produce a modified output value. They're utilized in templates to process data prior to showing it to users. Angular comes with built-in pipes for typical operations like Date, Number, Currency formatting, among others. Furthermore, it's possible to develop custom pipes tailored to your particular requirements.
Uses of Pipes:
- Formatting Data: Pipes are useful for shaping data into the desired format before it's shown. For instance, you can use them to format dates or numbers.
- Filtering Data: Pipes have the ability to sift through arrays based on specific conditions.
- Sorting Data: Pipes have the ability to organize arrays according to specific criteria.
- Custom Transformations: You have the ability to develop custom pipes for executing particular transformations on your data.
Parameterizing Pipes:
Pipes have the ability to take in parameters, which lets you tailor their functionality. This makes the pipe more adaptable and reusable. You can pass parameters to pipes using colons :
followed by the specific parameter values.
Pipes Vs. Directives:
- Pipes: Pipes serve the function of converting data right inside templates.
- Directives: Directives enhance DOM elements by introducing new behaviors. They have the ability to alter how elements look or act, such as by toggling visibility, adding or removing classes, and other similar actions.
Here's a sample to showcase how pipes are used in Angular:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{ today | date }}</h1>
<p>{{ amount | currency:'USD':true }}</p>
<ul>
<li *ngFor="let num of numbers | slice:0:3">{{ num }}</li>
</ul>
<p>{{ text | uppercase }}</p>
`
})
export class AppComponent {
today: Date = new Date();
amount: number = 1000;
numbers: number[] = [1, 2, 3, 4, 5];
text: string = "hello world";
}
In this example:
- The
date
pipe is used to format thetoday
date. - The
currency
pipe converts theamount
into USD format. - The
slice
pipe extracts the initial 3 digits from thenumbers
array. - The
uppercase
pipe changes thetext
into uppercase letters.
Exploring Pipes:
- Uppercase: Converts a string to uppercase.
- Lowercase: Converts a string to lowercase.
- Number: Displays a given number in text format, adding comma separators for thousands and including decimal places.
- Percent: Formats a number as a percentage.
- Currency: Formats a number as currency.
- Date: This formats a date based on the rules of the specific locale.
- Slice: Returns a portion of an array.
- Json: Transforms a JavaScript object or value into a JSON string.
<!-- Uppercase and Lowercase -->
<p>{{ 'Hello World' | uppercase }}</p>
<p>{{ 'Hello World' | lowercase }}</p>
<!-- Number, Percent, and Currency -->
<p>{{ 1000 | number }}</p>
<p>{{ 0.75 | percent }}</p>
<p>{{ 1000 | currency:'USD':true }}</p>
<!-- Date -->
<p>{{ today | date:'fullDate' }}</p>
<!-- Slice -->
<ul>
<li *ngFor="let num of numbers | slice:0:3">{{ num }}</li>
</ul>
<!-- Json -->
<p>{{ user | json }}</p>
Difference between Pure Pipes and Impure Pipes:
- Pure Pipes: Pure pipes are invoked by Angular only when there is a pure change in the input value, whether it's an immutable object or a primitive type. If the input reference remains unchanged, they do not recalculate the output.
- Impure Pipes: These types of pipes are invoked during every change detection cycle, even if the input value remains the same. They are particularly handy in situations where the pipe relies on frequently changing state.
The PipeTransform Interface:
In Angular, pipes implement the PipeTransform
interface to ensure a standard way of converting input data. This requires them to define the transform
method, which processes the input and provides the modified result.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'myCustomPipe' })
export class MyCustomPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
// Transformation logic here
}
}
Chaining Pipes:
In Angular, you can use multiple pipes in succession within the template by chaining them one after another.
<p>{{ 'hello world' | uppercase | slice:0:5 }}</p>
Create the custom pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'titleCase' })
export class TitleCasePipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value.toLowerCase().split(' ').map(word => {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
}
Using the custom pipe in a component:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{ title | titleCase }}</h1>
<p>{{ subtitle | titleCase }}</p>
`
})
export class AppComponent {
title: string = 'this is a custom pipe example';
subtitle: string = 'another example for custom pipe';
}
Add the custom pipe to the module:
Ensure you include the TitleCasePipe
in the declarations
array within your Angular module, often found in app.module.ts
:.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { TitleCasePipe } from './title-case.pipe'; // Import the custom pipe here
@NgModule({
declarations: [
AppComponent,
TitleCasePipe // Add the custom pipe to declarations
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
When you execute your Angular application, making use of the custom titleCase
pipe in your templates becomes possible. This pipe will transform any given string into title case.
<h1>{{ 'hello world' | titleCase }}</h1> <!-- Output: Hello World -->
<p>{{ 'angular is awesome' | titleCase }}</p> <!-- Output: Angular Is Awesome -->
Here's a simple illustration of how to build and utilize a custom pipe in Angular.