Sub topic 3
Formatting for a Locale
Assume you know TypeScript, Angular templates, standalone components, and the imports array. A locale is a regional convention for formatting dates, numbers, percentages, and currency. Angular uses LOCALE_ID to choose that convention.
Formatting for a locale
Register the locale data and provide its identifier in your application configuration:
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import { ApplicationConfig, LOCALE_ID } from '@angular/core';
registerLocaleData(localeDe);
export const appConfig: ApplicationConfig = {
providers: [{ provide: LOCALE_ID, useValue: 'de' }],
};With this configuration, built-in pipes such as date, number, percent, and currency use German conventions. For example, a number may display as 1.234,56 instead of 1,234.56.
Writing a custom pipe
A custom pipe is a class that implements PipeTransform. Its transform method receives the value before the pipe and returns the display value.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string | null, limit = 20): string {
if (!value) return '';
return value.length > limit
? value.slice(0, limit).trimEnd() + '…'
: value;
}
}Use it by importing it into a standalone component and writing {{ description | truncate:40 }}.
Pure versus impure pipes
Pipes are pure by default. Angular reruns a pure pipe when its input value or parameter changes. For arrays and objects, changing the contents in place does not change the reference, so the pipe might not run.
An impure pipe uses pure: false and runs during every change-detection cycle. This can observe in-place mutations, but it can also slow the application. Prefer immutable updates or a pure pipe whenever possible.
Using pipes in component code
A pipe is also a class. You can instantiate one and call transform directly:
import { DatePipe } from '@angular/common';
const formatted = new DatePipe('en-US').transform(
new Date(2024, 0, 15),
'yyyy-MM-dd',
);Unit testing a custom pipe
Because a pipe is a plain class, its transformation can usually be tested without TestBed:
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe', () => {
const pipe = new TruncatePipe();
it('truncates long text', () => {
expect(pipe.transform('abcdefghij', 5)).toBe('abcde…');
});
});Exercise
Why might a pure pipe fail to notice items.push(newItem)?
Show answer
The array reference stays the same. Replace the array with a new array, or use an impure pipe when that trade-off is justified.