Sub topic 2
Passing parameters to pipes
This chapter assumes you know basic TypeScript syntax, can write Angular components with interpolation, and know how a standalone component lists its dependencies in imports. It covers how a pipe receives parameters, what the main built-in pipes accept, and the errors that come up most often.
How parameters work
A pipe takes the value on its left as its first input. Any extra values come after a colon. Each colon starts the next parameter, in a fixed order.
<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>The syntax maps directly onto the pipe's transform method. In price | currency:'EUR':'symbol':'1.2-2', Angular calls transform(price, 'EUR', 'symbol', '1.2-2'). The value is the first argument. The parameters follow in the order you wrote them.
Three rules follow from this mapping:
- Parameters are positional. You cannot name them or skip one.
- Parameters are expressions. You can pass a literal, a component property, or a calculation such as
format(). - Parameters are optional when the pipe's signature gives them a default.
Literals and bindings
A parameter can be a string literal, a number, or a component field. A field lets the format change at runtime.
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-stamp',
standalone: true,
imports: [DatePipe],
template: `
<button (click)="toggle()">Switch format</button>
<p>{{ createdAt | date:format }}</p>
`,
})
export class StampComponent {
createdAt = new Date(2024, 0, 15, 9, 30);
format = 'shortDate';
toggle(): void {
this.format = this.format === 'shortDate' ? 'fullDate' : 'shortDate';
}
}Because the pipe is pure (more on that in a later chapter), Angular reruns it when any input changes. Changing format counts as a change, so the output updates.
Skipping a middle parameter
Since parameters are positional, to set the third you must supply the second. Pass undefined to get a default for the ones in between.
<p>{{ createdAt | date:'short':undefined:'de' }}</p>Here the timezone parameter is left at its default and the locale is set to German for this one expression.
Date pipe parameters
DatePipe accepts up to three parameters:
| Position | Meaning | Example |
|---|---|---|
| 1 | Format: a named preset or a pattern | `'mediumDate'`, `'yyyy-MM-dd'` |
| 2 | Timezone: an offset or `'UTC'` | `'UTC'`, `'+0530'` |
| 3 | Locale: overrides the app locale | `'fr'` |
Named presets such as short, medium, long, full, shortDate, mediumDate, longDate, fullDate, shortTime and mediumTime follow the active locale. Patterns do not adapt. 'MM/dd/yyyy' always prints month first, whatever the locale.
Pattern letters are case-sensitive, and this causes frequent mistakes:
MMis the month,mmis minutes.yyyyis the calendar year.YYYYis the week-based year, which can differ from the calendar year around 1 January.HHis a 24-hour clock,hhis a 12-hour clock and needsafor AM/PM.
<p>{{ createdAt | date:'yyyy-MM-dd HH:mm' }}</p>
<p>{{ createdAt | date:'hh:mm a' }}</p>
<p>{{ createdAt | date:'HH:mm':'UTC' }}</p>The input can be a Date, a number of milliseconds, or an ISO 8601 string. A string like '2024-01-15' without a time is treated as local midnight by the pipe, which avoids the off-by-one-day surprise that new Date('2024-01-15') causes in zones west of UTC.
Number, percent and currency parameters
DecimalPipe (named number), PercentPipe and CurrencyPipe share a digits-info string. Its format is:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}So '1.2-2' means at least one integer digit and exactly two fraction digits. '3.0-0' pads to three integer digits and shows no fraction.
<p>{{ 3.14159 | number:'1.2-4' }}</p> <!-- 3.1416 -->
<p>{{ 7 | number:'3.0-0' }}</p> <!-- 007 -->
<p>{{ 0.256 | percent:'1.0-1' }}</p> <!-- 25.6% -->
<p>{{ 1234.5 | number:'1.0-0' }}</p> <!-- 1,235 -->The pipe rounds the value, and it adds thousands separators according to the locale. When the digits-info string is omitted, number shows up to three fraction digits, and percent shows none.
PercentPipe multiplies by 100. Pass 0.256, not 25.6. Passing 25.6 prints 2,560%.
Currency parameters
CurrencyPipe takes the most parameters:
| Position | Meaning | Example |
|---|---|---|
| 1 | ISO 4217 currency code | `'USD'`, `'EUR'` |
| 2 | Display: `'symbol'`, `'symbol-narrow'`, `'code'`, or a custom string | `'code'` |
| 3 | Digits-info string | `'1.0-0'` |
| 4 | Locale | `'de'` |
<p>{{ 1234.5 | currency:'USD' }}</p> <!-- $1,234.50 -->
<p>{{ 1234.5 | currency:'USD':'code' }}</p> <!-- USD1,234.50 -->
<p>{{ 1234.5 | currency:'CAD':'symbol-narrow' }}</p> <!-- $1,234.50 -->
<p>{{ 1234.5 | currency:'EUR':'symbol':'1.0-0' }}</p> <!-- €1,235 -->If you omit the code, the pipe uses the DEFAULT_CURRENCY_CODE token, which is USD unless you provide another value. Currency is not converted, only formatted. A value of 10 with code 'EUR' prints as ten euros, whatever the number was meant to be.
import { ApplicationConfig, DEFAULT_CURRENCY_CODE } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [{ provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }],
};Parameters on other built-in pipes
Several simpler pipes also take parameters:
slice:start:endreturns part of an array or string, asArray.prototype.slicedoes.jsonanduppercasetake none.keyvalueaccepts an optional comparator function as its parameter.i18nPluralandi18nSelecttake a mapping object.
<p>{{ title | slice:0:10 }}</p>
<p>{{ items.length | i18nPlural: messages }}</p>The slice pipe is a quick truncation tool, but it counts UTF-16 code units. An emoji or a composed character may be cut in half. For user-facing text, a custom pipe (covered in a later chapter) gives you control.
Parameters and precedence
The pipe operator has low precedence. It binds more loosely than the ternary operator and almost everything else. This matters when a pipe is mixed with other operators.
<!-- Pipe applies to the whole ternary result -->
<p>{{ isSale ? salePrice : price | currency }}</p>
<!-- Pipe applies only to price; parentheses make intent clear -->
<p>{{ isSale ? salePrice : (price | currency) }}</p>In the first line, Angular parses it as isSale ? salePrice : (price | currency). Behavior here is easy to misread, so use parentheses whenever a pipe shares an expression with ?:, || or ??.
Parameters that are themselves pipe expressions need parentheses too:
<p>{{ createdAt | date:(useLong ? 'long' : 'short') }}</p>Without the parentheses, the ternary would not parse as one parameter.
Common errors
- Wrong order.
currency:'symbol':'EUR'swaps the code and the display. Angular may throw an error for the unknown currency display, or print a wrong symbol. - Invalid digits-info.
'2-4'or'1.2-'throwsNG02100: InvalidPipeArgumentat runtime. The string must matchmin.minFrac-maxFrac. - Passing a string where a number is expected.
numberaccepts numeric strings such as'12.5', but not'12,5'. A localized string throwsInvalidPipeArgument. - Missing locale data. Passing a locale like
'de'as a parameter requires that you calledregisterLocaleDatafor it. Without it, Angular reports that the locale data is missing. - Forgetting the import. In a standalone component, each pipe must be in
imports. IfDatePipeis not listed, the template fails to compile with an error that the pipedatecould not be found. - Expecting mutation. A pipe returns a new value for display. It never changes
createdAtorpriceon the component.
Worked example
This component shows an order line with several parameterized pipes. It uses a field for the digits format, so the precision can change.
import { CurrencyPipe, DatePipe, PercentPipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-order-line',
standalone: true,
imports: [CurrencyPipe, DatePipe, PercentPipe],
template: `
<p>Ordered: {{ orderedAt | date:'dd MMM yyyy, HH:mm':'UTC' }}</p>
<p>Unit price: {{ unitPrice | currency:'EUR':'symbol':digits }}</p>
<p>Discount: {{ discount | percent:'1.0-1' }}</p>
<p>Total: {{ total | currency:'EUR':'symbol':digits }}</p>
`,
})
export class OrderLineComponent {
orderedAt = new Date(Date.UTC(2024, 2, 5, 14, 7));
unitPrice = 19.99;
quantity = 3;
discount = 0.125;
digits = '1.2-2';
get total(): number {
return this.unitPrice * this.quantity * (1 - this.discount);
}
}With the default en-US locale, the output is:
- Ordered: 05 Mar 2024, 14:07
- Unit price: €19.99
- Discount: 12.5%
- Total: €52.47
The component keeps raw numbers and dates. The template decides how they look, and changing digits to '1.0-0' rounds both prices to whole euros without touching the data.
Exercise
What does {{ 0.4567 | percent:'1.1-2' }} print in the default en-US locale, and what would {{ 45.67 | percent:'1.1-2' }} print?
Show answer
The first prints 45.67%, because the pipe multiplies by 100 and shows between one and two fraction digits. The second prints 4,567% (4567.00 would need at least one fraction digit, so it prints 4,567% after trailing zeros are trimmed down to the minimum of one digit as 4,567.0%). The correct reading is that the value is multiplied by 100 again, giving 4,567.0%, so you should pass a ratio such as 0.4567.
Exercise
You want a date shown as the time only, in UTC, using the German locale for this one expression, without changing the app-wide locale. Write the template expression.
Show answer
{{ createdAt | date:'shortTime':'UTC':'de' }}. The format is the first parameter, the timezone the second and the locale the third. The German locale data must be registered with registerLocaleData first.