Sub topic 3
Chaining pipes
This chapter covers combining several pipes in one template expression, predicting the result, and fixing the errors that appear when the output of one pipe does not suit the next. It assumes you can write basic TypeScript, use interpolation in Angular templates, and import standalone pipes and components through the imports array. It also assumes you know how to pass parameters to a built-in pipe, such as date:'mediumDate'.
How a chain is evaluated
A chain is two or more pipes joined with |. Angular evaluates it from left to right. The first pipe receives the original value. Every later pipe receives the return value of the pipe before it.
<p>{{ createdAt | date:'fullDate' | uppercase }}</p>Suppose createdAt is new Date(2024, 0, 15) and the locale is en-US. The steps are:
date:'fullDate'turns theDateinto the stringMonday, January 15, 2024.uppercasereceives that string and returnsMONDAY, JANUARY 15, 2024.
Each pipe sees only the value passed to it. The uppercase pipe never learns that the text came from a date, and it does not see createdAt.
Parameters inside a chain
Each pipe in a chain takes its own parameters. Parameters follow the pipe name, separated by colons, and belong only to that pipe.
<p>{{ title | slice:0:30 | titlecase }}</p>
<p>{{ createdAt | date:'EEEE, d MMM y' | uppercase }}</p>Parameters can be expressions, such as a component property:
<p>{{ description | slice:0:maxLength | lowercase }}</p>The : separates parameters and the | separates pipes. A chain can mix the two freely: value | a:1:2 | b | c:'x'.
Chains also work in property bindings, and inside control flow blocks:
<h2 [title]="product.name | titlecase | truncate:25">{{ product.name | titlecase }}</h2>
@for (tag of tags | slice:0:3; track tag) {
<span class="tag">{{ tag | lowercase }}</span>
}The @for line shows that a pipe can sit in the collection expression. Here slice limits the list to three items, and lowercase is applied to each item separately in its own expression.
Order changes the result
A chain is not commutative. Two orders of the same pipes can give different output, or one order can fail.
<!-- Works: date returns a string, uppercase accepts a string -->
<p>{{ createdAt | date:'fullDate' | uppercase }}</p>
<!-- Fails at runtime: uppercase receives a Date, not a string -->
<p>{{ createdAt | uppercase | date:'fullDate' }}</p>In the second line, uppercase throws an error because a Date is not a string. Angular reports it as an InvalidPipeArgument error, with a message that names the pipe and the bad argument type.
Order matters even when both orders run without error. Consider slice and uppercase on the German word straße:
<p>{{ 'straße' | uppercase | slice:0:6 }}</p>
<p>{{ 'straße' | slice:0:6 | uppercase }}</p>The first line returns STRASS, because uppercasing turns ß into SS and makes the string longer before it is cut. The second line returns STRASSE, because the six-character slice runs first. Most text will not behave this way, but a transformation that changes length should come before a pipe that depends on length only when you want that effect.
A practical rule: put the pipe that changes the data type or shape first, and cosmetic pipes (case changes, truncation) last.
Types between pipes
Every built-in pipe declares the input types it accepts and the type it returns. When you chain, the return type of one pipe must match the accepted input of the next. The table shows the pipes from this tutorial that you will chain most often.
| Pipe | Accepts | Returns |
|---|---|---|
| `date` | `Date`, number, or ISO string; or `null`/`undefined` | `string` or `null` |
| `uppercase`, `lowercase`, `titlecase` | `string`, or `null`/`undefined` | `string` or `null` |
| `number`, `percent` | number or numeric string; or `null`/`undefined` | `string` or `null` |
| `currency` | number or numeric string; or `null`/`undefined` | `string` or `null` |
| `slice` | array or string; or `null`/`undefined` | array or string, or `null` |
| `json` | any value | `string` |
The number-formatting pipes return formatted strings such as 1,235 or $1,234.50. Those strings are for display. They are not numeric strings that another number pipe can parse.
<!-- Fails: number returns "1,235", and currency cannot read the comma as a numeric value -->
<p>{{ total | number:'1.0-0' | currency }}</p>To combine number formatting steps, put the one pipe with every setting you need:
<p>{{ total | currency:'USD':'symbol':'1.0-0' }}</p>Do the numeric work in the component (rounding, unit conversion) and use a single formatting pipe in the template. Chaining a formatting pipe with another formatting pipe is rarely the right design.
Null and undefined values
The built-in pipes listed above accept null and undefined, and they return null for them. The template then renders an empty string. That makes chains safe when data has not arrived yet:
<p>{{ user?.createdAt | date:'mediumDate' | uppercase }}</p>If user is undefined, user?.createdAt is undefined. The date pipe returns null, uppercase returns null, and the paragraph stays empty.
A custom pipe in the chain must handle this too. The TruncatePipe from the custom pipes chapter accepts string | null | undefined and returns an empty string when the value is missing. Because its input type allows null, it can follow any pipe that may return null:
<p>{{ createdAt | date:'fullDate' | truncate:12 }}</p>If a custom pipe declared its parameter as string only, strict template type checking would report an error here, because date may return null.
Chaining with the async pipe
The async pipe can start a chain, but the result is a value that may be null until the first emission. Parentheses make the grouping clear:
<p>{{ (price$ | async) | currency:'EUR' }}</p>
<p>{{ (user$ | async)?.name | titlecase }}</p>When you need the value more than once, subscribe a single time with @if ... as, then chain on the local name:
@if (user$ | async; as user) {
<h2>{{ user.name | titlecase }}</h2>
<p>Member since {{ user.createdAt | date:'mediumDate' | uppercase }}</p>
}Putting async several times in the same template subscribes several times. Each | async creates its own subscription, so for an HTTP request this can send multiple requests.
Parentheses and grouping
Add parentheses around any expression that contains operators, such as ?:, +, or &&, before you pipe it. The pipe operator interacts with those operators in ways that are easy to misread. Parentheses state your intent and do not depend on precedence rules.
<p>{{ (isDraft ? draftTitle : publishedTitle) | titlecase }}</p>
<p>{{ (firstName + ' ' + lastName) | uppercase }}</p>When the same chained value is needed in several places, store it with @let once:
@let heading = article.title | titlecase | truncate:40;
<h1>{{ heading }}</h1>
<title-badge [label]="heading" />Chaining and change detection
The built-in pipes and most custom pipes are pure. A pure pipe runs again only when its input value or any parameter changes by reference (for objects and arrays) or by value (for primitives). In a chain this applies to each pipe independently. If createdAt keeps the same Date object, the date pipe does not run again, and neither does uppercase, because its input is the same string.
This has one consequence for mutable data. If you change a Date in place with createdAt.setDate(20), the object reference is the same, so the chain does not update. Replace the value instead: createdAt = new Date(2024, 0, 20). Pure and impure pipes are covered in detail in a later chapter.
A complete example
This standalone component combines the pieces above. It uses async, a chain with parameters, and a pipe from the library @angular/common.
import { AsyncPipe, DatePipe, SlicePipe, TitleCasePipe, UpperCasePipe } from '@angular/common';
import { Component } from '@angular/core';
import { of } from 'rxjs';
interface Article {
title: string;
publishedAt: Date;
tags: string[];
}
@Component({
selector: 'app-article-card',
standalone: true,
imports: [AsyncPipe, DatePipe, SlicePipe, TitleCasePipe, UpperCasePipe],
template: `
@if (article$ | async; as article) {
<h2>{{ article.title | titlecase }}</h2>
<p>{{ article.publishedAt | date:'fullDate' | uppercase }}</p>
<p>
@for (tag of article.tags | slice:0:2; track tag) {
<span>{{ tag | uppercase }} </span>
}
</p>
}
`,
})
export class ArticleCardComponent {
article$ = of<Article>({
title: 'chaining pipes in angular',
publishedAt: new Date(2024, 0, 15),
tags: ['angular', 'pipes', 'templates'],
});
}The output is the title Chaining Pipes In Angular, the date MONDAY, JANUARY 15, 2024 (in an en-US locale), and the tags ANGULAR and PIPES. The third tag is cut off by slice:0:2.
Every pipe used in a template must be in the component's imports array. If you forget UpperCasePipe, the compiler reports that no pipe named uppercase was found.
Common errors
- A pipe was not found. The pipe is missing from
imports. Add the pipe class, such asDatePipe, to the component. InvalidPipeArgumentat runtime. A pipe received a type it does not accept. Check the order of the chain and the return type of the previous pipe.- A formatted number fed to another number pipe. Format once, as the last numeric step, and keep raw numbers in the component.
- The chain does not update after a mutation. Pure pipes track references. Assign a new object or array.
- An unexpected result from a conditional. Wrap the expression in parentheses before the first
|. - Several requests from one stream. Use a single
@if (x$ | async; as x)and chain onx.
Exercise
A template has {{ price | number:'1.2-2' | currency:'USD' }} and Angular throws an InvalidPipeArgument error for price = 1234.5. Explain why it fails and write a corrected version.
Show answer
The number pipe returns the display string 1,234.50, which includes a thousands separator. The currency pipe then receives a string that cannot be parsed as a number, so it throws. The fix is to remove the number pipe and set the digits in the currency pipe itself: {{ price | currency:'USD':'symbol':'1.2-2' }}, which shows $1,234.50.
Exercise
Write a template expression that shows createdAt as a medium date, in upper case, and that stays empty without an error when createdAt is null. Then explain why the pipes are in that order.
Show answer
{{ createdAt | date:'mediumDate' | uppercase }}. The date pipe must come first because it converts the Date into a string, and uppercase accepts only strings. Both built-in pipes accept null and return null, so the paragraph renders as empty text with no error. Reversing the order would pass a Date to uppercase and throw an InvalidPipeArgument error.
Exercise
A product list shows {{ isSale ? saleName : regularName | titlecase }}. You want titlecase to apply to whichever name is chosen. How do you write this so that the intent is clear, and how would you avoid repeating the expression if you needed the same value in three places?
Show answer
Wrap the conditional in parentheses: {{ (isSale ? saleName : regularName) | titlecase }}. To reuse the value, declare it once with @let name = (isSale ? saleName : regularName) | titlecase; and then use {{ name }} in each place.