Sub topic 10
Writing a custom pipe
Built-in pipes cover dates, numbers and text case. Sooner or later you need a format they don't offer, such as shortening a long description for a card. A custom pipe lets you write that logic once and reuse it in any template.
This chapter assumes you know basic TypeScript, Angular components with template interpolation, and standalone components with an imports array. It also assumes you know how to pass parameters to a built-in pipe.
The shape of a custom pipe
A custom pipe is a class with two parts:
- The
@Pipedecorator, which gives the pipe its template name. - A
transformmethod, required by thePipeTransforminterface, which receives the input value and returns the formatted result.
The following pipe shortens text to a given length.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string | null | undefined, limit = 20, ellipsis = '…'): string {
if (!value) {
return '';
}
return value.length > limit ? value.slice(0, limit).trimEnd() + ellipsis : value;
}
}The name in the decorator is what you type in a template after the | symbol. The class name does not matter to the template.
How arguments map to parameters
The first argument of transform is the value on the left of the pipe operator. Every further argument becomes a pipe parameter, written after a colon.
| Template expression | `value` | `limit` | `ellipsis` | Column |
|---|---|---|---|---|
| `description \ | truncate` | `description` | 20 (default) | `'…'` (default) |
| `description \ | truncate:40` | `description` | 40 | `'…'` (default) |
| `description \ | truncate:40:'...'` | `description` | 40 | `'...'` |
Default values make parameters optional, so callers only supply what they want to change.
Using the pipe in a component
A standalone pipe is made available by listing it in the imports array of the standalone component that uses it.
import { Component } from '@angular/core';
import { TruncatePipe } from './truncate.pipe';
@Component({
selector: 'app-summary',
standalone: true,
imports: [TruncatePipe],
template: `<p>{{ description | truncate:40 }}</p>`,
})
export class SummaryComponent {
description = 'A long description that will be shortened for display in a card.';
}The component keeps the full text. The template decides how much of it to show.
Design guidelines
- Handle
nullandundefinedin the input type. Values from Observables and optional fields often arrive empty, and the pipe should return a safe result such as an empty string. - Keep
transformfree of side effects. It should compute a result from its arguments and nothing else. - Give parameters sensible defaults so that the short form
value | truncateworks. - Choose a name that describes the result, in lowerCamelCase if it has several words.
A pipe that is not pure
By default a pipe is pure. Angular calls a pure pipe again only when its input value or a parameter changes by reference. If you push an item into an array, the array reference is the same, so a pure pipe that filters that array will not run again.
Setting pure: false makes Angular run the pipe on every change detection cycle.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'activeOnly', standalone: true, pure: false })
export class ActiveOnlyPipe implements PipeTransform {
transform(items: { name: string; active: boolean }[]): { name: string; active: boolean }[] {
return items.filter((item) => item.active);
}
}This pipe now reflects in-place changes, but it also runs, and builds a new array, far more often. Prefer a pure pipe and replace the array with a new one when data changes. The next chapter compares the two kinds in detail.
Exercise
You write a pipe with @Pipe({ name: 'shout', standalone: true }) and a class called ShoutingPipe. In a template you write {{ title | shout }}, but Angular reports that the pipe cannot be found. What is the most likely cause, and how do you fix it?
Show answer
The component that uses the pipe has not imported it. Add ShoutingPipe to the imports array of that standalone component. The template name shout comes from the decorator, so the class name does not need to match it.
Exercise
Using the TruncatePipe above, what does {{ 'abcdefghij' | truncate:5 }} render?
Show answer
It renders abcde…. The input has 10 characters, which is more than the limit of 5, so the pipe keeps the first 5 characters, trims trailing whitespace (none here) and appends the default ellipsis.