Sub topic 12
Formatting Values with Pipes
A pipe is a small function that takes a value in a template and returns a formatted version for display. Pipes keep formatting rules out of your component class, so the class holds raw data (a Date, a number, a string) and the template decides how it looks.
This chapter assumes you already know text interpolation, reading signals in templates, and the standalone imports array from earlier chapters.
Pipe Syntax
A pipe is applied with the | operator inside an interpolation or binding expression:
<p>{{ today | date }}</p>Angular evaluates today and passes the result to the date pipe's transform method. Whatever transform returns is what gets rendered.
Parameters
Pipes accept parameters after a colon. Each additional parameter gets another colon:
<p>{{ today | date: 'longDate' }}</p>
<p>{{ price | currency: 'EUR' : 'symbol' : '1.2-2' }}</p>Chaining
You can chain pipes. Each pipe receives the previous pipe's output:
<p>{{ today | date: 'fullDate' | uppercase }}</p>Precedence
The pipe operator binds more loosely than arithmetic and logical operators, so a + b | currency formats the sum. It binds more tightly than the ternary operator, so ok ? a : b | uppercase only uppercases b. Use parentheses when you mean something else:
<p>{{ (isVip ? vipName : guestName) | uppercase }}</p>Built-in Pipes
The common pipes ship in @angular/common. Each one is a standalone class that you import into the component that uses it.
| Pipe class | Template name | Example | Output | Column |
|---|---|---|---|---|
| `DatePipe` | `date` | `{{ d \ | date: 'shortTime' }}` | `10:00 AM` |
| `CurrencyPipe` | `currency` | `{{ 9.5 \ | currency }}` | `$9.50` |
| `DecimalPipe` | `number` | `{{ 3.14159 \ | number: '1.0-2' }}` | `3.14` |
| `PercentPipe` | `percent` | `{{ 0.256 \ | percent }}` | `26%` |
| `UpperCasePipe` / `LowerCasePipe` | `uppercase` / `lowercase` | `{{ 'Hi' \ | uppercase }}` | `HI` |
| `TitleCasePipe` | `titlecase` | `{{ 'angular pipes' \ | titlecase }}` | `Angular Pipes` |
| `SlicePipe` | `slice` | `{{ [1,2,3,4] \ | slice: 1 : 3 }}` | `2,3` |
| `JsonPipe` | `json` | `{{ user \ | json }}` | pretty-printed JSON |
| `KeyValuePipe` | `keyvalue` | `@for (e of obj \ | keyvalue; ...)` | `{ key, value }` pairs |
| `AsyncPipe` | `async` | `{{ data$ \ | async }}` | latest emitted value |
The digit format '1.0-2' means at least 1 integer digit, at least 0 fraction digits, and at most 2 fraction digits.
The date, currency, number, and percent pipes are locale-aware. They use the app's LOCALE_ID, which defaults to en-US. If you set another locale, you must also register its data with registerLocaleData from @angular/common, or the pipe throws at runtime.
A Component Using Built-in Pipes
import { Component, signal } from '@angular/core';
import {
AsyncPipe,
CurrencyPipe,
DatePipe,
KeyValuePipe,
PercentPipe,
TitleCasePipe
} from '@angular/common';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-order-summary',
imports: [AsyncPipe, CurrencyPipe, DatePipe, KeyValuePipe, PercentPipe, TitleCasePipe],
template: `
<h2>{{ customer() | titlecase }}</h2>
<p>Placed: {{ placedAt | date: 'medium' }}</p>
<p>Total: {{ total() | currency: 'USD' }}</p>
<p>Discount: {{ discount() | percent: '1.0-1' }}</p>
<ul>
@for (line of quantities | keyvalue; track line.key) {
<li>{{ line.key }}: {{ line.value }}</li>
}
</ul>
<p>Seconds on page: {{ seconds$ | async }}</p>
`
})
export class OrderSummaryComponent {
customer = signal('ada lovelace');
placedAt = new Date();
total = signal(1234.5);
discount = signal(0.125);
quantities = { pencils: 3, notebooks: 2 };
seconds$ = interval(1000).pipe(map(n => n + 1));
}Note that signals are called (total()) before the pipe runs. The pipe receives the value, not the signal.
The async pipe subscribes to an Observable or Promise, returns the latest value, and unsubscribes when the component is destroyed. Before the first emission it returns null.
Writing a Custom Pipe
A custom pipe is a class decorated with @Pipe that implements PipeTransform. From Angular 19, pipes are standalone by default, just like components.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string | null | undefined, limit = 20, suffix = '…'): string {
if (!value) {
return '';
}
return value.length > limit ? value.slice(0, limit).trimEnd() + suffix : value;
}
}The first argument of transform is the value on the left of |. Later arguments map, in order, to the colon-separated parameters. Use it like any other pipe:
import { Component } from '@angular/core';
import { TruncatePipe } from './truncate.pipe';
@Component({
selector: 'app-article-preview',
imports: [TruncatePipe],
template: `
<p>{{ body | truncate }}</p>
<p>{{ body | truncate: 40 : ' (more)' }}</p>
`
})
export class ArticlePreviewComponent {
body = 'Pipes keep formatting logic out of component classes and in reusable units.';
}Type the value parameter to accept null and undefined. Values often start empty, for example while data loads or before async emits. A pipe that crashes on null breaks the whole template.
Pure and Impure Pipes
Pipes are pure by default. Angular calls a pure pipe's transform only when its input value or a parameter changes. For objects and arrays, "changes" means a new reference, checked with ===.
This makes pure pipes cheap. It also causes the most common pipe bug:
// The template uses {{ items | sortByName }}
this.items.push(newItem); // same array reference: the pure pipe does NOT rerun
this.items = [...this.items, newItem]; // new reference: the pipe rerunsSignals already push you toward the second style, because signal.update(list => [...list, item]) produces a new array.
You can mark a pipe impure with @Pipe({ name: 'x', pure: false }). Angular then calls it on every change detection cycle, which can mean many times per second. async and keyvalue are impure for this reason. Write impure pipes only when you must track internal mutation or external state, and keep their transform fast.
Common Errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `NG0302: The pipe 'date' could not be found` | Pipe not in the component's `imports` | Import `DatePipe` (or your pipe class) | |
| Pipe output stale after adding to a list | Array mutated in place, pure pipe skipped | Replace the array with a new reference | |
| `Missing locale data for the locale "de-DE"` | `LOCALE_ID` set without registered data | Call `registerLocaleData(localeDe)` | |
| Ternary formats only one branch | `\ | ` binds tighter than `? :` | Wrap the ternary in parentheses |
| Template shows `[object Object]` | Interpolating an object directly | Use `json` for debugging, or format fields |
Exercise
Write a pure pipe named initials that turns 'grace brewster hopper' into 'GBH', returns an empty string for null or undefined, and accepts an optional max parameter limiting the number of letters. Then show how to use it with a limit of 2 and what that renders.
Show answer
@Pipe({ name: 'initials' }) export class InitialsPipe implements PipeTransform { transform(value: string | null | undefined, max = Infinity): string { if (!value) return ''; return value.split(/\s+/).filter(Boolean).map(w => w[0].toUpperCase()).slice(0, max).join(''); } }. Add InitialsPipe to the component's imports, then write {{ name | initials: 2 }}, which renders GB.
Exercise
A template shows {{ tags | joinTags }} with a custom pure pipe. The class runs this.tags.push('new') and the displayed text does not change. Explain why and give two fixes.
Show answer
A pure pipe reruns only when its input reference changes. push mutates the same array, so Angular skips transform. The better fix is to assign a new array (this.tags = [...this.tags, 'new'], or use a signal with update(t => [...t, 'new'])). The other fix is to mark the pipe pure: false, which costs performance because it then runs on every change detection cycle.
Exercise
What does {{ loggedIn ? user.name : 'guest' | uppercase }} render when loggedIn is true and user.name is 'Lin', and how do you uppercase both branches?
Show answer
It renders Lin, because the pipe applies only to 'guest'. Write {{ (loggedIn ? user.name : 'guest') | uppercase }} to uppercase both branches.