Skip to main content

Pipes

Pipes are used to transform data in Angular. There are several built-in pipes in Angular, but you can also create your own custom pipes.

Built-in Pipes

DatePipe

The DatePipe is used to format dates. For example, the following code formats the current date:

import { Component } from '@angular/core';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
today = new Date();
}
<p>{{ today | date }}</p>

The following code formats the current date using the short date format:

<p>{{ today | date: 'shortDate' }}</p>

UpperCasePipe

The UpperCasePipe is used to transform text to uppercase. For example, the following code transforms the text to uppercase:

<p>{{ 'Hello' | uppercase }}</p>

LowerCasePipe

The LowerCasePipe is used to transform text to lowercase. For example, the following code transforms the text to lowercase:

<p>{{ 'Hello' | lowercase }}</p>

CurrencyPipe

The CurrencyPipe is used to format currency. For example, the following code formats the number 1000 as currency:

<p>{{ 1000 | currency }}</p>

DecimalPipe

The DecimalPipe is used to format numbers. For example, the following code formats the number 1000 as a decimal number:

<p>{{ 1000 | number }}</p>

PercentPipe

The PercentPipe is used to format numbers as percentages. For example, the following code formats the number 0.5 as a percentage:

<p>{{ 0.5 | percent }}</p>

Creating Custom Pipes

You can also create your own custom pipes. For example, the following code creates a custom pipe that transform the first letter of a string to uppercase:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
<p>{{ 'hello' | capitalize }}</p>

Chaining Pipes

You can chain pipes. For example, the following code transforms the text to uppercase and then capitalizes the first letter of the text:

<p>{{ 'hello' | uppercase | capitalize }}</p>

Async Pipes

The AsyncPipe is used to subscribe to an Observable or Promise. For example, the following code subscribes to an Observable:

import { Component } from '@angular/core';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
title$ = of('Home');
}
<p>{{ title$ | async }}</p>

Pipes vs. Directives

Pipes are used to transform data, while directives are used to add or remove elements from the DOM.

Pipes vs. Services

Pipes are used to transform data, while services are used to fetch data from a server.