Sub topic 12
Using Pipes in Component Code
Pipes usually appear in templates. Sometimes the formatted value is needed in TypeScript instead, for example a page title, an accessible label, a log message, or text for a CSV export. This chapter shows how to call a pipe from component code, how to supply its dependencies, and when a different tool fits better.
This chapter assumes you know basic TypeScript, standalone components with an imports array, and the inject() function. It also assumes you have used date, currency and custom pipes in templates.
A pipe is a class with a transform method
A pipe has no special runtime form. It is a class with a transform method, and the template syntax value | date:'yyyy-MM-dd' calls transform(value, 'yyyy-MM-dd') for you. In code you make that call yourself.
The simplest approach is to create an instance and call the method.
import { DatePipe } from '@angular/common';
const datePipe = new DatePipe('en-US');
const formatted = datePipe.transform(new Date(2024, 0, 15), 'yyyy-MM-dd');
// formatted === '2024-01-15'The string passed to the constructor is the locale. It plays the role that LOCALE_ID plays in a template. If you leave it out, TypeScript reports an error, because the constructor requires a locale.
Parameters that appear after a colon in a template become extra arguments to transform, in the same order.
| Template | Code | Column |
|---|---|---|
| `price \ | currency:'EUR':'symbol':'1.2-2'` | `currencyPipe.transform(price, 'EUR', 'symbol', '1.2-2')` |
| `ratio \ | percent:'1.0-1'` | `percentPipe.transform(ratio, '1.0-1')` |
| `d \ | date:'mediumDate'` | `datePipe.transform(d, 'mediumDate')` |
Return types include null
The built-in DatePipe, CurrencyPipe, DecimalPipe and PercentPipe return string | null. They return null when the input is null, undefined or an empty string. In a template this is harmless, because null renders as nothing. In code, the type forces you to decide what to do.
import { DatePipe } from '@angular/common';
const datePipe = new DatePipe('en-US');
function dueLabel(due: Date | null): string {
const text = datePipe.transform(due, 'longDate') ?? 'No due date';
return `Due: ${text}`;
}Your own pipes can return whatever type you choose. The TruncatePipe from the custom pipe chapter always returns a string, so it needs no such fallback.
Getting the locale and defaults through dependency injection
Hard-coding 'en-US' defeats the app-wide locale setting. The built-in pipes are also decorated so that Angular can construct them, and they read LOCALE_ID and related tokens in their constructors. Two patterns let you reuse that configuration.
Pattern 1: provide the pipe and inject it
Built-in pipes are not provided in the root injector. You must list the pipe in a providers array before you can inject() it. After that, Angular builds the pipe with the app's locale, default time zone and default currency code.
import { Component, inject } from '@angular/core';
import { CurrencyPipe, DatePipe } from '@angular/common';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-order-summary',
standalone: true,
providers: [DatePipe, CurrencyPipe],
template: `<p [attr.aria-label]="label">{{ label }}</p>`,
})
export class OrderSummaryComponent {
private readonly datePipe = inject(DatePipe);
private readonly currencyPipe = inject(CurrencyPipe);
private readonly title = inject(Title);
readonly label: string;
constructor() {
const placed = this.datePipe.transform(new Date(2024, 0, 15), 'mediumDate');
const total = this.currencyPipe.transform(1234.5, 'EUR');
this.label = `Order placed ${placed}, total ${total}`;
this.title.setTitle(this.label);
}
}Putting the providers on the component limits each instance to that component and its children. If several components need the same pipe, list it in providers of your ApplicationConfig instead.
Pattern 2: inject the locale and construct the pipe
When you want a pipe in a plain service, or you want to avoid the provider entry, inject LOCALE_ID and pass it yourself.
import { Injectable, LOCALE_ID, inject } from '@angular/core';
import { DatePipe } from '@angular/common';
@Injectable({ providedIn: 'root' })
export class DateFormatter {
private readonly datePipe = new DatePipe(inject(LOCALE_ID));
short(value: Date | string | number | null | undefined): string {
return this.datePipe.transform(value, 'short') ?? '';
}
}This service now follows whatever locale the application configures. The approach has one gap. The constructor's optional second and third arguments (a default time zone and default options) are not filled from the injector. If your app sets DATE_PIPE_DEFAULT_OPTIONS, only Pattern 1 picks it up automatically.
Non-English locales need registered data
A pipe constructed with 'de' fails, or falls back to the wrong output, unless the German locale data has been registered. Registration is a one-time call, usually in main.ts or in the file that defines the app configuration.
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { CurrencyPipe, DatePipe } from '@angular/common';
registerLocaleData(localeDe);
const germanDate = new DatePipe('de').transform(new Date(2024, 0, 15), 'mediumDate');
// '15.01.2024'
const germanPrice = new CurrencyPipe('de').transform(1234.5, 'EUR');
// '1.234,50 €'Without registerLocaleData, Angular throws an error saying that locale data for de was not found. Only en-US data is built in.
Functions instead of pipe classes
@angular/common also exports plain functions that do the same work without creating an object: formatDate, formatNumber, formatPercent and formatCurrency. They take the locale as an explicit argument.
import { formatDate, formatNumber } from '@angular/common';
const day = formatDate(new Date(2024, 0, 15), 'yyyy-MM-dd', 'en-US');
// '2024-01-15'
const amount = formatNumber(1234.5678, 'en-US', '1.2-2');
// '1,234.57'These functions never return null. They throw an error if the value cannot be converted. Choose them when you already have a locale string and want a compact, dependency-free call. Choose the pipe class when you want the same defaults the templates use, or when you need to call a custom pipe through one shared interface.
Using a custom pipe in code
A custom pipe is also an ordinary class, so you can instantiate it directly when it has no constructor dependencies. You can also provide it and inject it, which is the better choice when the pipe itself depends on a service.
import { TruncatePipe } from './truncate.pipe';
const truncate = new TruncatePipe();
const preview = truncate.transform('A long description that will be shortened', 20);
// 'A long description t…'If your pipe gets a service through inject() in a field initializer, new TruncatePipe() outside an injection context throws. Provide the pipe and inject it so that Angular constructs it.
Choosing between template and code
The following diagram summarizes the decision.
Prefer the template whenever the output is only displayed. The template keeps raw data in the component and lets you change the presentation without touching logic. Move to code when the text is not part of the template content, such as the document title, a console message, a file name, or a value passed to a third-party library.
Avoid calling pipes from template methods
A common mistake is to write a component method that wraps a pipe and call it from the template.
<p>{{ formatDue(task.due) }}</p>Angular calls formatDue on every change detection pass, and nothing caches the result. A pure pipe in the template runs only when its input changes. When a list shows many rows, the method form repeats work that the template pipe would have skipped. If the formatted string is needed in both places, compute it once, for example in a computed() signal or when the data arrives, and bind the result.
import { Component, computed, inject, signal } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-task-due',
standalone: true,
providers: [DatePipe],
template: `<p>{{ dueLabel() }}</p>`,
})
export class TaskDueComponent {
private readonly datePipe = inject(DatePipe);
readonly due = signal<Date | null>(new Date(2024, 0, 15));
readonly dueLabel = computed(
() => this.datePipe.transform(this.due(), 'fullDate') ?? 'No due date',
);
}The computed value is recalculated only when due changes, which gives you the same caching a pure template pipe provides.
The async pipe is not for code
The async pipe depends on the change detection machinery of a view. It needs a template context to mark the view for checking and to unsubscribe when the view is destroyed. In component code, subscribe to the observable yourself, or convert it with toSignal.
Common errors
| Symptom | Likely cause | Column |
|---|---|---|
| `NullInjectorError: No provider for DatePipe` | The pipe was injected but not listed in a `providers` array | |
| `NG0203: inject() must be called from an injection context` | `inject()` was called inside an event handler or callback | |
| Locale data for `de` not found | `registerLocaleData` was never called for that locale | |
| Output is in English although `LOCALE_ID` is `de` | The pipe was built with a hard-coded `'en-US'` | |
| `Type 'string \ | null' is not assignable to type 'string'` | The null return was not handled with `??` or a check |
Exercise
A service builds the string Total: 1.234,50 € for a German user by calling new CurrencyPipe('de').transform(1234.5, 'EUR'). In production the call throws an error about missing locale data. What is missing, and where should it be added?
Show answer
The German locale data was never registered. Import localeDe from @angular/common/locales/de and call registerLocaleData(localeDe) once at startup, for example in main.ts or next to the application configuration, before any pipe uses the 'de' locale.
Exercise
Why is {{ formatDue(task.due) }}, where formatDue wraps DatePipe, slower in a long list than {{ task.due | date:'fullDate' }}, and how can you keep the code-based formatting without that cost?
Show answer
A method call in the template runs on every change detection pass for every row, while a pure pipe runs again only when its input value changes. To keep formatting in code, compute the string once, for example in a computed() signal or when the data is loaded, and bind that stored result in the template.