A pipe formats a value in the template, like a price, a date or a percentage. This part covers the built-in pipes, dates and time zones, writing your own pipe, pure and impure pipes, and when computed is the better tool.
A price is stored as 1234.5. On the page it should read $1,234.50. A date is stored as a Date object; on the page it should read March 5, 2026. Angular’s tool for “show this value in a nicer way” is called a pipe.
This part covers the built-in pipes from @angular/common, number, currency and date formats, the time zone trap with dates, chaining pipes, writing your own pipe, and why a pure pipe runs so rarely. We’ll also compare a pipe with computed() from Part 3 and with a method call. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
Paste this into src/app/app.ts:
// src/app/app.ts
import { CurrencyPipe, PercentPipe, TitleCasePipe } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [CurrencyPipe, PercentPipe, TitleCasePipe],
template: `
<p>{{ name() | titlecase }}</p>
<p>{{ price() | currency }}</p>
<p>{{ discount() | percent }}</p>
`,
})
export class App {
protected readonly name = signal('ada lovelace');
protected readonly price = signal(1234.5);
protected readonly discount = signal(0.256);
}
Before you read on, guess. What do the three lines say? In particular: how many digits does the percentage have?
Here’s what happens. The page shows:
Ada Lovelace
$1,234.50
26%
titlecase made each word start with a capital letter, and it lowercases the rest of each word, so McDonald would become Mcdonald. currency added a dollar sign, a comma between thousands and exactly two decimal places. percent multiplied by 100 and rounded to a whole number: 25.6% became 26%. To get 25.6%, you ask for it. We’ll see how below.
None of this changed the signals. price() is still 1234.5. A pipe only changes what’s shown.
What a pipe is
A pipe takes a value and returns a new value to show. In a template, you write it after the value, with a | between them. That’s the same character JavaScript uses for “bitwise or”, but in a template Angular reads it as “pass the value through this pipe”. Pipes work in double curly braces and in property bindings like [title]="price() | currency":
{{ value | pipeName }}
{{ value | pipeName: firstArg : secondArg }}
Some pipes take arguments: extra settings that come after the name, each one after a colon. {{ 3.14159 | number: '1.2-2' }} passes the argument '1.2-2' to the number pipe.
A pipe is a class. To use one in a template, the component lists it in imports, like a child component in Part 5. The built-in pipes come from @angular/common:
| In the template | Class to import | What it does |
|---|---|---|
uppercase, lowercase, titlecase |
UpperCasePipe, LowerCasePipe, TitleCasePipe |
change letter case |
number |
DecimalPipe |
format a number |
percent |
PercentPipe |
format a fraction as a percentage |
currency |
CurrencyPipe |
format money |
date |
DatePipe |
format a date and time |
slice |
SlicePipe |
part of a string or a list |
json |
JsonPipe |
show any value as JSON text |
keyvalue |
KeyValuePipe |
turn an object into a list of key/value pairs |
async |
AsyncPipe |
the latest value of an Observable (Part 20) |
Note that the name in the template doesn’t always match the class: number is DecimalPipe. If you forget the import, the build stops. We’ll read that error in a worked example.
Numbers: the ‘1.2-2’ format
number, percent and currency all take a format string for the digits. It has three parts: '{minimum whole digits}.{minimum decimals}-{maximum decimals}'. So '1.2-2' means “at least 1 digit before the point, and exactly 2 after it”.
// src/app/app.ts
import { DecimalPipe, PercentPipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
imports: [DecimalPipe, PercentPipe],
template: `
<p>{{ 3.14159 | number }}</p>
<p>{{ 3.14159 | number: '1.2-2' }}</p>
<p>{{ 3 | number: '1.2-2' }}</p>
<p>{{ 3.14159 | number: '3.0-1' }}</p>
<p>{{ 1234567.891 | number }}</p>
<p>{{ 2.5 | number: '1.0-0' }}</p>
<p>{{ 0.256 | percent: '1.1-1' }}</p>
`,
})
export class App {}
The page shows:
3.142
3.14
3.00
003.1
1,234,567.891
3
25.6%
Line by line:
- With no format,
numbershows up to 3 decimals:3.142. '1.2-2'gives exactly two:3.14, and3becomes3.00.'3.0-1'pads the whole part to three digits and keeps at most one decimal:003.1.numberadds commas between thousands.'1.0-0'rounds to a whole number.2.5became3: halves round up.percenttakes the same format.'1.1-1'gives the25.6%that the first example lost.
percent with no format is '1.0-0', which is why we got 26%.
Money: currency code and display
currency takes up to three arguments, in this order: the currency code, how to display it, and the digits format.
// src/app/app.ts
import { CurrencyPipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
imports: [CurrencyPipe],
template: `
<p>{{ 1234.5 | currency }}</p>
<p>{{ 1234.5 | currency: 'EUR' }}</p>
<p>{{ 1234.5 | currency: 'EUR' : 'code' }}</p>
<p>{{ 1234.5 | currency: 'CAD' }}</p>
<p>{{ 1234.5 | currency: 'CAD' : 'symbol-narrow' }}</p>
<p>{{ 1234.5 | currency: 'JPY' }}</p>
<p>{{ 1234.5 | currency: 'USD' : 'symbol' : '1.0-0' }}</p>
`,
})
export class App {}
The page shows:
$1,234.50
€1,234.50
EUR1,234.50
CA$1,234.50
$1,234.50
¥1,235
$1,235
- The code is a three-letter ISO 4217 code:
USD,EUR,CAD,JPY. With no code,currencyusesUSD, the default value of theDEFAULT_CURRENCY_CODEtoken, which an app can change. - The display is
'symbol'(the default),'code', or'symbol-narrow'. A Canadian dollar’s symbol isCA$, so it isn’t mixed up with a US dollar. The narrow symbol is just$. Only use it when the page makes clear which dollar you mean. - Each currency has its own number of decimals. Yen have none, so
¥1,235. - The digits format works as for
number.'1.0-0'drops the cents.
The thousands comma, the decimal point and where the symbol goes all come from the locale: the language and region the app formats for. Angular’s default locale is en-US, so every example here uses US formats. We’ll see another locale at the end of the dates section.
Dates, and the time zone trap
date formats a Date, a number of milliseconds, or a date string. It takes a format, then a time zone:
// src/app/app.ts
import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
imports: [DatePipe],
template: `
<p>{{ when | date: 'medium' : 'UTC' }}</p>
<p>{{ when | date: 'short' : 'UTC' }}</p>
<p>{{ when | date: 'longDate' : 'UTC' }}</p>
<p>{{ when | date: 'fullDate' : 'UTC' }}</p>
<p>{{ when | date: 'shortTime' : 'UTC' }}</p>
<p>{{ when | date: 'yyyy-MM-dd HH:mm' : 'UTC' }}</p>
<p>{{ when | date: 'medium' : '+0530' }}</p>
<p>{{ when | date: 'medium' : '-0500' }}</p>
`,
})
export class App {
protected readonly when = new Date('2026-03-05T14:30:00Z');
}
'2026-03-05T14:30:00Z' is one exact moment: 14:30 on 5 March 2026, in UTC (the Z at the end means UTC). The page shows:
Mar 5, 2026, 2:30:00 PM
3/5/26, 2:30 PM
March 5, 2026
Thursday, March 5, 2026
2:30 PM
2026-03-05 14:30
Mar 5, 2026, 8:00:00 PM
Mar 5, 2026, 9:30:00 AM
The first six lines are named formats and one custom format. In a custom format, yyyy is the year, MM the month, dd the day, HH the hour from 0 to 23 and mm the minutes. Letters have meanings, so MM (month) and mm (minutes) are different things.
The last two lines are the same moment in two other zones: India (5 hours 30 minutes ahead of UTC) and New York in winter (5 hours behind).
Now the trap. Without a time zone argument, date uses the time zone of the reader’s computer. That’s often what you want: a reader in New York sees New York time. But it means the same page shows different text to different people. We can’t even tell you what {{ when | date: 'medium' }} prints on your screen. On the machine that checked this post, which is set to India time, it printed Mar 5, 2026, 8:00:00 PM. In New York it prints Mar 5, 2026, 9:30:00 AM.
Two more things can bite:
- The time zone argument takes an offset like
'+0530'or'+05:30','UTC'or'GMT', or a US abbreviation like'EST'. Anything else, such as'America/New_York','CET'or'IST', is quietly ignored, and the reader’s zone is used. There’s no error. This line proves it, whatever your zone is:
// src/app/app.ts
import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
imports: [DatePipe],
template: `
<p>{{ (when | date: 'medium' : 'America/New_York') === (when | date: 'medium') }}</p>
<p>{{ '2026-03-05' | date }}</p>
`,
})
export class App {
protected readonly when = new Date('2026-03-05T14:30:00Z');
}
The page shows:
true
Mar 5, 2026
The ( ) around each pipe make === compare the two results. Without them, the second | would take everything to its left as its input.
- A plain date has no time. The second line passes the string
'2026-03-05'. Thedatepipe reads a string with no time as midnight in the reader’s own zone, so it shows March 5 everywhere. That’s what you want for a birthday or a due date. Be careful with JavaScript’snew Date('2026-03-05'), though: JavaScript reads that as midnight UTC, which is still March 4 in New York. For a plain date, either keep the string and pass no time zone, or usenew Date('2026-03-05')and always pass'UTC'. Never mix the two: the string with'UTC'shows March 4 to readers east of London, such as in India.
So, the rule: for a moment in time, decide whose clock it should be shown in. If it’s the reader’s, leave the zone out and accept that the text differs per reader. If it’s a fixed offset, like UTC, pass it. An offset doesn’t follow daylight saving, though: New York is -0500 in winter but -0400 from 8 March to 1 November 2026. To show a named zone with its summer time, the date pipe isn’t enough. JavaScript’s Intl.DateTimeFormat with a timeZone option, such as 'America/New_York', is, and you can call it in a computed. For a calendar date, don’t turn it into a moment at all.
Another locale
The number, percent, currency and date pipes take a last argument for the locale. Only en-US is built in. Try 'de' (German) without anything else:
// src/app/app.ts
import { DecimalPipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
imports: [DecimalPipe],
template: `<p>{{ 1234.5 | number: '1.2-2' : 'de' }}</p>`,
})
export class App {}
It builds, but the paragraph stays empty and the console shows an error:
ERROR RuntimeError: NG02100: InvalidPipeArgument: 'NG0701: Missing locale data for the locale "de".' for pipe '_DecimalPipe'
The rules for each locale live in their own files, so an app only ships the ones it uses. You register one with registerLocaleData:
// src/app/app.ts
import { CurrencyPipe, DecimalPipe, registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { Component } from '@angular/core';
registerLocaleData(localeDe);
@Component({
selector: 'app-root',
imports: [CurrencyPipe, DecimalPipe],
template: `
<p>{{ 1234.5 | number: '1.2-2' : 'de' }}</p>
<p>{{ 1234.5 | currency: 'EUR' : 'symbol' : undefined : 'de' }}</p>
`,
})
export class App {}
The page shows:
1.234,50
1.234,50 €
German swaps the point and the comma, and puts the euro sign after the number. The undefined skips the digits argument so we can reach the locale. A whole app in one language sets its locale once instead, with a LOCALE_ID provider, and still registers that locale’s data. That’s part of internationalisation, which this series doesn’t cover.
Chaining pipes
The result of one pipe can go into another. They run left to right:
// src/app/app.ts
import { DatePipe, SlicePipe, UpperCasePipe } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [DatePipe, SlicePipe, UpperCasePipe],
template: `
<p>{{ when() | date: 'longDate' : 'UTC' | uppercase }}</p>
<p>{{ 'Angular' | slice: 0 : 3 | uppercase }}</p>
`,
})
export class App {
protected readonly when = signal(new Date('2026-03-05T14:30:00Z'));
}
The page shows:
MARCH 5, 2026
ANG
slice: 0 : 3 works like JavaScript’s slice: from index 0 up to, not including, index 3. Order matters. uppercase can’t go before date, because it expects text and when() is a Date, and the build would say so.
Here’s the first line as a picture. The right side is about when a pipe runs again, which the next sections prove.
A value goes through each pipe in turn, left to right in the template, top to bottom here. Each pipe remembers its last input and result.
Writing your own pipe
The built-in pipes cover numbers, money, dates and case. Anything else, you write. Let’s make a pipe that turns Ada Lovelace into AL. Make a new file src/app/initials-pipe.ts:
// src/app/initials-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
transform(name: string, max = 2): string {
return name
.split(' ')
.filter((word) => word !== '')
.map((word) => word[0].toUpperCase())
.slice(0, max)
.join('');
}
}
and use it in src/app/app.ts:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { InitialsPipe } from './initials-pipe';
@Component({
selector: 'app-root',
imports: [InitialsPipe],
template: `
<p>{{ name() | initials }}</p>
<p>{{ name() | initials: 3 }}</p>
`,
})
export class App {
protected readonly name = signal('grace brewster hopper');
}
The page shows:
GB
GBH
Here’s what each piece does:
@Pipe({ name: 'initials' })marks the class as a pipe and gives the name used in templates. Pipe names are written in lowerCamelCase, likeinitialsorrelativeSize. They can’t contain a-.transformis the method Angular calls. Its first parameter is the value on the left of the|. Every parameter after that is an argument, in order:initials: 3callstransform(name, 3).implements PipeTransformis TypeScript. It asks the compiler to check that the class really has atransformmethod. It’s optional, but it catches a typo in the method name.max = 2is a default value: when the template passes no argument,maxis 2. TypeScript works out from the 2 thatmaxis a number.- The file is
initials-pipe.tsand the class isInitialsPipe, following the style guide’s naming for pipes.
The parameter types are checked in the template, like everything else. We’ll see that in a worked example.
Pure pipes run only when their input changes
Let’s watch when transform runs. Add a console.log to the pipe:
// src/app/initials-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
transform(name: string, max = 2): string {
console.log(`initials(${name}, ${max})`);
return name
.split(' ')
.filter((word) => word !== '')
.map((word) => word[0].toUpperCase())
.slice(0, max)
.join('');
}
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { InitialsPipe } from './initials-pipe';
@Component({
selector: 'app-root',
imports: [InitialsPipe],
template: `
<p>{{ name() | initials: max() }}</p>
<button (click)="nothing()">Do nothing</button>
<button (click)="name.set('alan turing')">Alan</button>
<button (click)="max.set(1)">One letter</button>
`,
})
export class App {
protected readonly name = signal('grace brewster hopper');
protected readonly max = signal(2);
protected nothing() {}
}
When the page loads, the console shows:
initials(grace brewster hopper, 2)
Click Do nothing three times. Each click is an event in the template, so Angular checks the component again, as we saw in Part 3. The console shows nothing new. Now click Alan, then One letter:
initials(alan turing, 2)
initials(alan turing, 1)
The page shows:
A
Do nothingAlanOne letter
(The three buttons sit on one line, so the page text runs them together.)
That’s a pure pipe, and every pipe is pure unless you say otherwise. On each check, Angular compares the input and every argument with the ones from last time. If all are the same, it reuses the last result and doesn’t call transform. If any changed, it calls transform again.
“The same” uses the same comparison as signals in Part 3: for text and numbers, the value; for a list or an object, the reference. That has a consequence you’ve met before.
Changing a list in place hides it from a pure pipe
Here’s a pipe that adds up a list of prices, and two ways to add an item:
// src/app/sum-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sum' })
export class SumPipe implements PipeTransform {
transform(prices: readonly number[]): number {
console.log(`sum of ${prices.length}`);
return prices.reduce((total, price) => total + price, 0);
}
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { SumPipe } from './sum-pipe';
@Component({
selector: 'app-root',
imports: [SumPipe],
template: `
<p>{{ prices().join(' + ') }} = {{ prices() | sum }}</p>
<button (click)="pushFive()">Push 5</button>
<button (click)="addFive()">Add 5</button>
`,
})
export class App {
protected readonly prices = signal([2, 3]);
protected pushFive() {
this.prices.update((list) => {
list.push(5);
return list;
});
}
protected addFive() {
this.prices.update((list) => [...list, 5]);
}
}
readonly number[] is a list of numbers the pipe promises not to change. Click Push 5. The page shows:
2 + 3 + 5 = 5
Push 5Add 5
The list shows the 5, because join runs on every check. The sum is still 5, because sum got the same array as last time and wasn’t called. The console shows only the line from page load:
sum of 2
Now click Add 5, which makes a new array:
2 + 3 + 5 + 5 = 15
Push 5Add 5
sum of 4
It’s the rule from Part 3 again: give signals, inputs and pipes a new array or object, and never change one in place.
Impure pipes run on every check
You can turn the comparison off with pure: false. Change only the decorator line of initials-pipe.ts:
// src/app/initials-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'initials', pure: false })
export class InitialsPipe implements PipeTransform {
transform(name: string, max = 2): string {
console.log(`initials(${name}, ${max})`);
return name
.split(' ')
.filter((word) => word !== '')
.map((word) => word[0].toUpperCase())
.slice(0, max)
.join('');
}
}
Use the app.ts with the three buttons from before:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { InitialsPipe } from './initials-pipe';
@Component({
selector: 'app-root',
imports: [InitialsPipe],
template: `
<p>{{ name() | initials: max() }}</p>
<button (click)="nothing()">Do nothing</button>
<button (click)="name.set('alan turing')">Alan</button>
<button (click)="max.set(1)">One letter</button>
`,
})
export class App {
protected readonly name = signal('grace brewster hopper');
protected readonly max = signal(2);
protected nothing() {}
}
Load the page and click Do nothing three times. The console shows:
initials(grace brewster hopper, 2)
initials(grace brewster hopper, 2)
initials(grace brewster hopper, 2)
initials(grace brewster hopper, 2)
One line for the first render and one for every click, even though nothing changed. An impure pipe runs every time Angular checks the component. Here that’s cheap. In a list of 500 rows, with a pipe that sorts or filters, it’s 500 calls on every click anywhere in the component.
Angular has a few impure pipes of its own. json, keyvalue and slice are impure, so they notice changes made in place. async is impure because its result changes whenever the stream sends a new value, with the same input. You’ll rarely write one. A pipe needs pure: false only when its result depends on something other than its input and arguments, and in modern Angular that “something” should usually be a signal read in a computed instead.
A pipe, computed, or a method call?
There are three ways to show a formatted value. Here they are side by side, each logging when it runs:
// src/app/shout-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'shout' })
export class ShoutPipe implements PipeTransform {
transform(value: string): string {
console.log(`pipe(${value})`);
return value.toUpperCase() + '!';
}
}
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
import { ShoutPipe } from './shout-pipe';
@Component({
selector: 'app-root',
imports: [ShoutPipe],
template: `
<p>{{ name() | shout }}</p>
<p>{{ shouted() }}</p>
<p>{{ shout(name()) }}</p>
<button (click)="nothing()">Do nothing</button>
<button (click)="name.set('ben')">Ben</button>
`,
})
export class App {
protected readonly name = signal('ana');
protected readonly shouted = computed(() => {
console.log(`computed(${this.name()})`);
return this.name().toUpperCase() + '!';
});
protected shout(value: string) {
console.log(`method(${value})`);
return value.toUpperCase() + '!';
}
protected nothing() {}
}
When the page loads, all three run once:
pipe(ana)
computed(ana)
method(ana)
Click Do nothing twice. Only the method runs, once per click:
method(ana)
method(ana)
Click Ben. All three run, because the name changed:
pipe(ben)
computed(ben)
method(ben)
A method call in a template runs on every check of the component. Angular can’t know whether a method’s result could change, so it has to ask each time. The pipe and the computed both remember their result.
So which one?
- A pipe when the same formatting is used in many templates: a price, a date, initials. You write it once and use it anywhere with
| name. computedwhen the value belongs to this one component, or is worked out from several signals: a cart total, a filtered list, a label made from three fields. It’s cached, it’s plain TypeScript, and you can use it in the class too, not just the template.- A method call only for something trivial. It’s fine for
isLast(i). It’s a slow page waiting to happen for anything that loops over a list.
The async pipe
async takes an Observable, a stream of values from the RxJS library, or a Promise, and shows its latest value. It subscribes when the binding first runs, subscribes again if you hand it a different Observable, and unsubscribes when the component is destroyed. You’ll see {{ users$ | async }} all over older Angular code, because it was the main way to show data from a server. In a new project, you usually turn the Observable into a signal with toSignal and read it like any other signal. Part 20 covers Observables, toSignal and the async pipe.
Worked example: an order summary
Let’s put the built-in pipes to work. An order has a date, a few lines, a discount and a currency. The totals are computed, and the pipes only format them:
// src/app/app.ts
import { CurrencyPipe, DatePipe, PercentPipe } from '@angular/common';
import { Component, computed, signal } from '@angular/core';
interface OrderLine {
name: string;
quantity: number;
price: number;
}
@Component({
selector: 'app-root',
imports: [CurrencyPipe, DatePipe, PercentPipe],
template: `
<h2>Order placed {{ placedOn() | date: 'fullDate' }}</h2>
<ul>
@for (line of lines(); track line.name) {
<li>
{{ line.quantity }} × {{ line.name }}: {{ line.price * line.quantity | currency: 'EUR' }}
</li>
}
</ul>
<p>Subtotal: {{ subtotal() | currency: 'EUR' }}</p>
<p>Discount: {{ discount() | percent: '1.0-1' }} (−{{ saving() | currency: 'EUR' }})</p>
<p>Total: {{ total() | currency: 'EUR' : 'code' }}</p>
<p>Shipped {{ shippedAt() | date: 'MMM d, HH:mm' : 'UTC' }} UTC</p>
`,
})
export class App {
protected readonly placedOn = signal('2026-03-05');
protected readonly shippedAt = signal(new Date('2026-03-06T09:15:00Z'));
protected readonly discount = signal(0.125);
protected readonly lines = signal<OrderLine[]>([
{ name: 'Notebook', quantity: 3, price: 4.5 },
{ name: 'Fountain pen', quantity: 1, price: 38 },
{ name: 'Ink', quantity: 2, price: 7.25 },
]);
protected readonly subtotal = computed(() =>
this.lines().reduce((sum, line) => sum + line.price * line.quantity, 0),
);
protected readonly saving = computed(() => this.subtotal() * this.discount());
protected readonly total = computed(() => this.subtotal() - this.saving());
}
The page shows:
Order placed Thursday, March 5, 2026
3 × Notebook: €13.50
1 × Fountain pen: €38.00
2 × Ink: €14.50
Subtotal: €66.00
Discount: 12.5% (−€8.25)
Total: EUR57.75
Shipped Mar 6, 09:15 UTC
Some things to notice:
line.price * line.quantity | currency: 'EUR'formats the result of the multiplication. The pipe has lower priority than*,+and the other operators, so everything to its left is its input.placedOnis a plain date, kept as a string, so it says Thursday for every reader.shippedAtis a moment, so the template says which clock it’s shown in, and the text says so too.- The money is worked out in
computedvalues and formatted at the last step. Never format and then calculate:'€58.00'is text, and you can’t add text up. 12.5%needed'1.0-1'. With plainpercentit would show13%, and the customer would wonder where the other half percent went.
Worked example: a truncate pipe with arguments
Long titles break card layouts. A truncate pipe cuts text to a length and adds an ending. It takes two arguments, both with defaults:
// src/app/truncate-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(text: string, limit = 20, ending = '…'): string {
if (text.length <= limit) {
return text;
}
return text.slice(0, limit).trimEnd() + ending;
}
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { TruncatePipe } from './truncate-pipe';
@Component({
selector: 'app-root',
imports: [TruncatePipe],
template: `
<p>{{ title() | truncate }}</p>
<p>{{ title() | truncate: 12 }}</p>
<p>{{ title() | truncate: 12 : ' (more)' }}</p>
<p>{{ 'Short title' | truncate }}</p>
`,
})
export class App {
protected readonly title = signal('A Very Long Book Title That Does Not Fit');
}
The page shows:
A Very Long Book Tit…
A Very Long…
A Very Long (more)
Short title
trimEnd() removes spaces at the end, so we don’t get A Very Long … with a gap before the dots.
Now a teammate uses it with a limit typed in a form, so it arrives as text, '12'. Change only app.ts:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { TruncatePipe } from './truncate-pipe';
@Component({
selector: 'app-root',
imports: [TruncatePipe],
template: `<p>{{ title() | truncate: limit() }}</p>`,
})
export class App {
protected readonly title = signal('A Very Long Book Title That Does Not Fit');
protected readonly limit = signal('12');
}
The build stops:
✘ [ERROR] TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. [plugin angular-compiler]
8 │ template: `<p>{{ title() | truncate: limit() }}</p>`,
TS2345 means “this argument has the wrong type”. The template compiler checked the call to transform the same way TypeScript checks a call in a .ts file. transform says limit is a number (from the default 20), and limit() is a string. Without the check, text.length <= '12' would compare a number with a string, and the bug would show up later as odd cuts. The fix is to store a number: signal(12), or convert where the text comes in with Number(...).
Worked example: a pipe that wasn’t imported
This is the error everyone meets in their first week with pipes. The template uses currency, but nobody imported CurrencyPipe:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>Total: {{ total() | currency }}</p>`,
})
export class App {
protected readonly total = signal(42);
}
ng serve stops with:
✘ [ERROR] NG8004: No pipe found with name 'currency'.
To fix this, import the "CurrencyPipe" class from "@angular/common" and add it to the "imports" array of the component. [plugin angular-compiler]
6 │ template: `<p>Total: {{ total() | currency }}</p>`,
Read it piece by piece:
NG8004is Angular’s code for “a pipe name in the template doesn’t match any pipe this component knows”.No pipe found with name 'currency'gives the name as written in the template. If you made a typo,| curency, you’d see that here. For a typo the “To fix this” line doesn’t appear, because there’s no pipe to suggest.- The second line names the class and the package to import it from. That’s the part to remember: the template name is
currency, but the class isCurrencyPipe. - The last line shows the template with
currencyunderlined. (In the real output, the file path with your project’s folder sits between the message and the code line.)
The same error comes up for your own pipes when you forget to add them to imports. Fix it by adding the import:
// src/app/app.ts
import { CurrencyPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [CurrencyPipe],
template: `<p>Total: {{ total() | currency }}</p>`,
})
export class App {
protected readonly total = signal(42);
}
The page shows:
Total: $42.00
The opposite mistake is a warning, not an error: a pipe in imports that the template doesn’t use. If some imports are used, the build prints NG8113: CurrencyPipe is not used within the template of App. If none are, it prints NG8113: All imports are unused. Either way, remove it from imports.
In older code
Before standalone components, pipes were declared in an NgModule: declarations: [InitialsPipe] in a @NgModule, with standalone: false (or, before Angular 19, nothing) in @Pipe. Components got the built-in pipes by importing CommonModule, which brings in every pipe and the old *ngIf and *ngFor directives at once. You’ll often see imports: [CommonModule] in standalone components too. It still works. Importing the pipes you use, one by one, says what the template needs. You’ll also see standalone: true written in @Pipe; since Angular 19 that’s the default, so new code leaves it out.
Best practices
- Import each pipe you use, by class.
imports: [CurrencyPipe, DatePipe]says exactly what the template needs, and an unused one gets a warning. It replacesimports: [CommonModule]. - Calculate in
computed, format with a pipe. Totals, discounts and filtered lists arecomputed; the pipe is the last step before the screen. It replaces formatting in a method and then trying to do maths on text. - Always decide the time zone for a moment in time. Pass
'UTC'or an offset like'+0530'when the zone is fixed, or leave it out on purpose for the reader’s own clock. It replaces finding out from a user in another country. - Keep custom pipes pure, and give them typed parameters with defaults. Pure pipes run only when their input changes, and typed parameters let the build catch a wrong argument. It replaces
pure: falseandany. - Prefer a pipe or
computedto a method call in the template. Both are cached; a method runs on every check. It replaces{{ formatPrice(item) }}.
Tips and traps
- Forgetting to import the pipe. The build stops with NG8004,
No pipe found with name 'currency'. Add the class it names (CurrencyPipe) toimports. - Percentages that lose a digit.
{{ 0.125 | percent }}shows13%. Pass a digits format:percent: '1.0-1'. - A time zone name as the argument.
date: 'medium' : 'America/New_York'builds, runs and quietly uses the reader’s zone. Use'UTC'or an offset like'-0500', and remember an offset ignores daylight saving. For a named zone, useIntl.DateTimeFormatwithtimeZone. - A date that’s a day off.
new Date('2026-03-05')is midnight UTC, which is March 4 in zones behind UTC. And'2026-03-05' | date: 'mediumDate' : 'UTC'is March 4 in zones ahead of it. Keep the string with no zone, or theDatewith'UTC', never the string with'UTC'. - Changing a list in place. A pure pipe gets the same array and keeps its old result, so a total stops updating. Give it a new array:
[...list, item]. - A missing locale.
number: '1.2-2' : 'de'shows nothing and logsNG0701: Missing locale data. CallregisterLocaleDatawith the locale’s data first. pure: falseto “fix” a stale pipe. It works, by running the pipe on every check. The real fix is a new reference, or acomputed.
A pipe changes how a value looks, not what it is, and a pure pipe runs only when its input or an argument changes.
Exercises
Exercise 1. This page should show Score: 87.5%, but shows something else. What does it show, and what’s the smallest fix?
// src/app/app.ts
import { PercentPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [PercentPipe],
template: `<p>Score: {{ score() | percent }}</p>`,
})
export class App {
protected readonly score = signal(0.875);
}
Exercise 2. Write a pipe relativeSize that turns a number of bytes into text: below 1024 it shows 512 B, below 1024 × 1024 it shows kilobytes with one decimal (1.5 KB), and above that megabytes with one decimal (2.4 MB). Give it an argument decimals that defaults to 1. Use it for 512, 1536 and 2500000 bytes, and once with relativeSize: 0 on 2500000. Hint: value.toFixed(1) gives a number as text with one decimal.
Exercise 3. Without running it, how many sum of lines does the console show after the page loads and you click Add 1, then Rename, then Rename again?
// src/app/sum-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sum' })
export class SumPipe implements PipeTransform {
transform(prices: readonly number[]): number {
console.log(`sum of ${prices.length}`);
return prices.reduce((total, price) => total + price, 0);
}
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { SumPipe } from './sum-pipe';
@Component({
selector: 'app-root',
imports: [SumPipe],
template: `
<p>{{ label() }}: {{ prices() | sum }}</p>
<button (click)="prices.update((list) => [...list, 1])">Add 1</button>
<button (click)="label.set('Total')">Rename</button>
`,
})
export class App {
protected readonly label = signal('Sum');
protected readonly prices = signal([2, 3]);
}
Answers
1. It shows Score: 88%. percent with no format rounds to a whole number, and 87.5 rounds up. Ask for one decimal:
// src/app/app.ts
import { PercentPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [PercentPipe],
template: `<p>Score: {{ score() | percent: '1.1-1' }}</p>`,
})
export class App {
protected readonly score = signal(0.875);
}
The page shows:
Score: 87.5%
2. One way to write it:
// src/app/relative-size-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'relativeSize' })
export class RelativeSizePipe implements PipeTransform {
transform(bytes: number, decimals = 1): string {
if (bytes < 1024) {
return `${bytes} B`;
}
if (bytes < 1024 * 1024) {
const kb = bytes / 1024;
return `${kb.toFixed(decimals)} KB`;
}
const mb = bytes / (1024 * 1024);
return `${mb.toFixed(decimals)} MB`;
}
}
// src/app/app.ts
import { Component } from '@angular/core';
import { RelativeSizePipe } from './relative-size-pipe';
@Component({
selector: 'app-root',
imports: [RelativeSizePipe],
template: `
<p>{{ 512 | relativeSize }}</p>
<p>{{ 1536 | relativeSize }}</p>
<p>{{ 2500000 | relativeSize }}</p>
<p>{{ 2500000 | relativeSize: 0 }}</p>
`,
})
export class App {}
The page shows:
512 B
1.5 KB
2.4 MB
2 MB
3. Two lines. The page load runs sum once. Add 1 makes a new array, so sum runs again. Rename changes label, so Angular checks the component, but the sum pipe gets the same array as last time and isn’t called. The second Rename is still a click, so Angular checks the component again, but label didn’t change and sum gets the same array, so nothing is logged. Here’s the run:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { SumPipe } from './sum-pipe';
@Component({
selector: 'app-root',
imports: [SumPipe],
template: `
<p>{{ label() }}: {{ prices() | sum }}</p>
<button (click)="prices.update((list) => [...list, 1])">Add 1</button>
<button (click)="label.set('Total')">Rename</button>
`,
})
export class App {
protected readonly label = signal('Sum');
protected readonly prices = signal([2, 3]);
}
// src/app/sum-pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sum' })
export class SumPipe implements PipeTransform {
transform(prices: readonly number[]): number {
console.log(`sum of ${prices.length}`);
return prices.reduce((total, price) => total + price, 0);
}
}
sum of 2
sum of 3
and the page shows:
Total: 6
Add 1Rename
What’s next
Pipes, like the directives in Part 11, are small reusable pieces you add to a template. In Part 13, we’ll look at how classes get the things they need, like a shared store or an HTTP client, with @Service() and inject().