Sub topic 12
Using pipes in component code
Pipes are not limited to templates. Each one is a plain TypeScript class with a transform method, so you can call it from a component, a service, or a test. This chapter assumes you know basic TypeScript, Angular standalone components and their imports array, and the built-in DatePipe and custom pipes from earlier chapters.
Why call a pipe from code
A template pipe only affects what the template displays. Sometimes you need the formatted value somewhere else:
- A page title set through the
Titleservice. - A string passed to an API, a log message, or a file name.
- A label built from several values before it reaches the template.
- A value that a function must compute, not only display.
In these cases you create the pipe and call transform yourself.
Calling a built-in pipe
DatePipe takes the locale as its first constructor argument. After that, transform accepts the same value and parameters you would write after the colons in a template.
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 template expression {{ value | date:'yyyy-MM-dd' }} is the same call as datePipe.transform(value, 'yyyy-MM-dd'). Each colon-separated parameter becomes the next argument.
Use the diagram below to compare the two paths.
Using dependency injection
Creating a pipe with new means you must pass the locale yourself. A better approach in an Angular app is to provide the pipe and let Angular inject it. Pipes from @angular/common are not provided by default, so list DatePipe in the providers array of the component or application.
import { DatePipe } from '@angular/common';
import { Component, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-report',
standalone: true,
providers: [DatePipe],
template: `<h1>Report</h1>`,
})
export class ReportComponent {
private readonly datePipe = inject(DatePipe);
private readonly title = inject(Title);
constructor() {
const today = this.datePipe.transform(new Date(), 'mediumDate');
this.title.setTitle(`Report for ${today}`);
}
}An injected DatePipe reads LOCALE_ID from the injector. If you registered German locale data and provided LOCALE_ID as 'de', the injected pipe formats dates in German. A pipe created with new DatePipe('en-US') ignores that setting and uses the locale you passed.
Calling a custom pipe
Your own pipes work the same way. The TruncatePipe from the custom pipe chapter has no dependencies, so you can create it directly.
import { TruncatePipe } from './truncate.pipe';
const truncate = new TruncatePipe();
const label = truncate.transform('A long product description', 10);
// label === 'A long pro…'If a custom pipe injects other services, create it through the injector instead of new. Add it to providers and use inject, as with DatePipe above.
Common errors
NullInjectorError: No provider for DatePipe. You calledinject(DatePipe)without listing it inproviders. Add it to the component or toApplicationConfig.- Wrong locale in the output. A pipe created with
newuses the locale argument you gave it, notLOCALE_ID. Pass the correct locale or inject the pipe. nullreturn value.DatePipe.transformreturnsnullfornull,undefined, or an empty string. Handle that case before you build a string from the result, or you will see the textnull.- Pipe called in a loop or getter. A getter that calls
transformruns on every change detection cycle. Compute the value once, for example when the data arrives, and store it in a field.
Summary of the approach
- Decide whether the value is needed outside the template.
- If so, provide the pipe and inject it, or create it with
newwhen it has no dependencies and you control the locale. - Call
transformwith the value followed by the same parameters you would use in the template. - Handle
nullresults.
Exercise
A component injects DatePipe with inject(DatePipe) and the app provides LOCALEID as 'de', but the build fails at runtime with NullInjectorError for DatePipe. What is missing, and what does a pipe created with new DatePipe('en-US') do about LOCALEID?
Show answer
DatePipe is not provided automatically, so add it to the providers array of the component or the application config. A pipe created with new DatePipe('en-US') ignores LOCALE_ID and always formats with the locale passed to its constructor, here en-US.