Sub topic 1
What Pipes Are and How to Apply Them
Prerequisites
This chapter assumes you already know three things:
- Basic TypeScript syntax: classes, properties, and simple types.
- Angular components and template interpolation with
{{ }}. - Angular standalone components and their
importsarray.
You do not need to know anything about custom pipes or RxJS. Those come in later chapters.
What a pipe is
A pipe is a small function that takes a value in a template and returns a new value for display. The component keeps the raw data. The template decides how to present it.
Consider a component with a createdAt property that holds a Date. If you print it with plain interpolation, you get the browser's default string for that date, which is long and not meant for users. A pipe lets you format it in the template without changing the stored value.
<p>{{ createdAt | date:'mediumDate' }}</p>The | character is the pipe operator. The value on its left is the input. The name on its right is the pipe to apply. Angular passes the input to the pipe's transform method and renders whatever that method returns.
This separation has practical benefits:
- The component can sort, compare, and send the raw value to a server. It never has to hold a formatted copy.
- Changing a display format means editing a template, not the data logic.
- The same pipe can be reused in many templates.
Where you can use the pipe operator
Pipes work inside template expressions. That includes interpolation, property bindings, and the new control flow blocks.
<p>{{ name | titlecase }}</p>
<input [value]="name | uppercase" />
@if ((count | number) !== '0') {
<p>Items: {{ count | number }}</p>
}Notice the parentheses in the @if condition. The pipe operator has lower precedence than almost every other operator, including the ternary ?: and comparison operators. Without parentheses, the pipe can end up applying to a larger expression than you meant.
You cannot use pipes in places that are not template expressions. Event bindings are a common mistake. A statement such as (click)="save(value | uppercase)" is not valid, because event handlers accept statements, not pipe expressions. Do the transformation in the component method instead. A later chapter covers calling a pipe from TypeScript.
Making pipes available in a standalone component
A standalone component can only use the pipes it imports. Many common pipes are exported by @angular/common. You add each one to the component's imports array.
import { Component } from '@angular/core';
import { DatePipe, TitleCasePipe } from '@angular/common';
@Component({
selector: 'app-profile',
standalone: true,
imports: [DatePipe, TitleCasePipe],
template: `
<h2>{{ name | titlecase }}</h2>
<p>Joined {{ joinedAt | date:'mediumDate' }}</p>
`,
})
export class ProfileComponent {
name = 'ada lovelace';
joinedAt = new Date(2024, 0, 15);
}The class names end in Pipe, such as DatePipe. The names you write in the template are lowercase, such as date. These two names are easy to mix up. You import the class and you use the template name.
If you forget the import, Angular reports an error that the pipe cannot be found. In recent versions the error is something like NG8004: No pipe found with name 'date'. The fix is always to add the matching class to imports.
Passing parameters
Most pipes accept parameters. You write each one after a colon. Separate several parameters with more colons.
<p>{{ createdAt | date:'mediumDate' }}</p>
<p>{{ price | currency:'EUR':'symbol':'1.2-2' }}</p>
<p>{{ ratio | percent:'1.0-1' }}</p>
<p>{{ name | titlecase }}</p>Each parameter maps to an argument of the pipe's transform method, in order. The first value, the one on the left of the |, is always the first argument. The parameters you write fill in the arguments after it.
For the currency line above, the pipe receives these values:
| Position | Value | Meaning |
|---|---|---|
| Input | `price` | The number to format |
| Parameter 1 | `'EUR'` | The currency code |
| Parameter 2 | `'symbol'` | Show a symbol such as `€` instead of the code |
| Parameter 3 | `'1.2-2'` | Digits info: at least 1 integer digit, exactly 2 fraction digits |
Parameters can be any template expression, not only literals. You can bind them to component properties so the format can change at run time.
<p>{{ createdAt | date:dateFormat }}</p>If you want to skip an optional parameter but set a later one, pass undefined for the one you skip.
<p>{{ price | currency:'USD':undefined:'1.0-0' }}</p>Details about each built-in pipe's parameters come in the chapters on dates and numbers. For now, the point is the syntax.
Chaining pipes
You can apply several pipes in a row. Angular evaluates them from left to right. The output of one pipe becomes the input of the next.
<p>{{ createdAt | date:'fullDate' | uppercase }}</p>Here the date pipe turns the Date into a string such as Monday, January 15, 2024. The uppercase pipe then receives that string and returns MONDAY, JANUARY 15, 2024.
Order matters, because each pipe expects a certain type of input. This chain fails:
<p>{{ createdAt | uppercase | date:'fullDate' }}</p>The uppercase pipe would receive a Date object, which is not a string. In development, Angular reports an error because the pipe's input type does not match. Even if it did not, the date pipe would then be given a string it could not format correctly. When you chain pipes, check what type each step produces.
Pipes and null values
Real data is often missing for a moment, for example while it loads. Built-in pipes handle this in a defined way. The date, number, percent, and currency pipes return null when the input is null or undefined, so the template prints nothing. The text case pipes behave the same way for null and undefined.
<p>Joined: {{ user?.joinedAt | date:'mediumDate' }}</p>If user is not yet set, the safe navigation operator ?. yields undefined, and the date pipe returns null. The paragraph shows Joined: with nothing after it and does not throw an error.
Passing a value of the wrong type is different. Giving the uppercase pipe a number, for example, raises a runtime error that names the pipe and the invalid argument. Use TypeScript types and the strict template checking setting to catch these mistakes at build time.
Precedence and parentheses
The pipe operator binds more loosely than other operators. This causes surprises with the ternary operator, as in this example.
<p>{{ isAdmin ? adminName : userName | uppercase }}</p>The pipe applies only to userName, because it binds tighter than the ternary here. If you want the whole result uppercased, add parentheses.
<p>{{ (isAdmin ? adminName : userName) | uppercase }}</p>The same rule applies when a pipe's result feeds another operator. Use parentheses around a piped expression whenever you combine it with ||, ??, +, comparisons, or function arguments. It costs nothing and makes the intent clear.
<p>{{ (price | currency) + ' per month' }}</p>Pipes with function arguments
A pipe can appear inside a method call's argument list too, provided it is wrapped properly.
<button [disabled]="isLocked(createdAt | date:'yyyy-MM-dd')">Edit</button>This works, but it runs the formatting on every evaluation of the binding. Keep such expressions small. If the logic grows, compute the value in the component instead.
A complete worked example
The following component combines the ideas from this chapter: imports, parameters, chaining, and null-safe use.
import { Component } from '@angular/core';
import {
CurrencyPipe,
DatePipe,
PercentPipe,
TitleCasePipe,
UpperCasePipe,
} from '@angular/common';
interface Order {
customer: string;
placedAt: Date;
total: number;
discount: number;
}
@Component({
selector: 'app-order-card',
standalone: true,
imports: [CurrencyPipe, DatePipe, PercentPipe, TitleCasePipe, UpperCasePipe],
template: `
@if (order) {
<h2>{{ order.customer | titlecase }}</h2>
<p>{{ order.placedAt | date:'fullDate' | uppercase }}</p>
<p>Total: {{ order.total | currency:'EUR':'symbol':'1.2-2' }}</p>
<p>Discount: {{ order.discount | percent:'1.0-1' }}</p>
}
`,
})
export class OrderCardComponent {
order: Order | null = {
customer: 'grace hopper',
placedAt: new Date(2024, 0, 15),
total: 1234.5,
discount: 0.125,
};
}With the default en-US locale, the template renders:
Grace HopperMONDAY, JANUARY 15, 2024Total: €1,234.50Discount: 12.5%
The component stores 1234.5 and 0.125. Only the template turns them into display text. If you later need to sort orders by total, the number is still a number.
Common errors
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `No pipe found with name 'date'` | The pipe class is missing from the component's `imports` | Add `DatePipe` to `imports` | |
| A pipe affects more of the expression than intended | Low precedence of `\ | ` | Wrap the part you want transformed in parentheses |
| Error about an invalid argument for a pipe | The input has the wrong type, such as a number given to `uppercase` | Convert the value first, or fix the type | |
| Pipe in an event handler fails to compile | Event bindings accept statements, not pipe expressions | Transform inside the component method | |
| Wrong parameter seems to be ignored | Parameters are positional | Count the colons, and pass `undefined` for skipped ones |
Summary of the syntax
value | pipeNameapplies a pipe.value | pipeName:arg1:arg2passes parameters, in order.value | a | bchains pipes from left to right.(expression) | pipeNameuses parentheses to control what the pipe receives.- In a standalone component, import the pipe class and use its lowercase template name.
Exercise
A template contains {{ isNew ? 'new item' : title | titlecase }}. When isNew is true, the output is new item in lowercase, not New Item. Explain why, and write the corrected expression.
Show answer
The pipe operator has lower precedence than the ternary operator in this position, so titlecase is applied only to the title branch. When isNew is true, the first branch returns 'new item' with no pipe applied. Wrap the ternary in parentheses so the pipe receives the whole result: {{ (isNew ? 'new item' : title) | titlecase }}.
Exercise
You write {{ createdAt | date:'fullDate' | uppercase }} in a standalone component that imports only DatePipe. What error do you expect, and what do you change?
Show answer
Angular reports that no pipe named uppercase was found, because the component's imports array does not contain UpperCasePipe. Add UpperCasePipe to imports, importing it from @angular/common. The date pipe still works because DatePipe is already imported.
Exercise
Given price = 1234.5, write a template expression that shows $1,234.50 with the currency pipe, setting the code to USD and the digits info to 1.2-2 but leaving the display parameter at its default.
Show answer
{{ price | currency:'USD':undefined:'1.2-2' }}. The second parameter, display, is skipped by passing undefined, so its default is used. The fourth parameter sets the digits info. With the default en-US locale, the output is $1,234.50.