Sub topic 10
Writing a custom pipe
Built-in pipes cover dates, numbers, and text case. Real applications also need formats the framework doesn't know about: file sizes, truncated text, initials, or phone numbers. A custom pipe lets you write that formatting once and reuse it in any template.
This chapter assumes you know basic TypeScript, Angular components with interpolation, and standalone components with their imports array. It also assumes you have used built-in pipes with parameters, such as date:'mediumDate'.
What a custom pipe is
A pipe is a class with two parts:
- The
@Pipedecorator, which gives the pipe its template name. - A
transformmethod, which receives the value on the left of|and any parameters after it. It returns the value to display.
Implementing the PipeTransform interface is optional at runtime, but it makes the compiler check that transform has a compatible signature.
A first pipe: truncate
This pipe shortens long text and appends an ellipsis.
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;
}
}Four details in this class matter:
name: 'truncate'is the identifier you type in templates. It does not have to match the class name, but it must be a valid JavaScript identifier. Names such asmy-pipedo not work.- The first parameter,
value, is always the left-hand side of the pipe. The remaining parameters are the pipe's own parameters. limitandellipsishave default values, so both are optional in the template.- The type
string | null | undefinedmatters because templates often pass values that are not loaded yet. The pipe returns an empty string in that case instead of throwing.
In Angular 19 and later, standalone: true is the default and you can omit it. Writing it explicitly is harmless and works in earlier versions.
Making the pipe available in a template
A standalone pipe is not global. Each standalone component that uses it must list it in imports.
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 template passes 40 as the first parameter, so limit is 40. The output is the first 40 characters, trimmed, followed by ….
If you forget the imports entry, compilation fails with an error like NG8004: No pipe found with name 'truncate'. This is the most common mistake with custom pipes. Check the import before you check the pipe's code.
Parameters
Each parameter after the first argument of transform maps to one colon-separated value in the template, in order.
<p>{{ description | truncate }}</p>
<p>{{ description | truncate:40 }}</p>
<p>{{ description | truncate:40:'...' }}</p>
<p>{{ description | truncate:undefined:'...' }}</p>The first line uses both defaults. The second sets the limit. The third sets both. The fourth passes undefined to keep the default limit while changing the ellipsis, because positional parameters cannot be skipped. JavaScript applies a default value when the argument is undefined, so this works. It does not apply when the argument is null.
Parameters can be any template expression, including component properties:
<p>{{ description | truncate:maxLength }}</p>You can chain a custom pipe with built-in pipes. Pipes apply left to right:
<p>{{ description | truncate:40 | uppercase }}</p>Here truncate runs first, then uppercase receives its result.
A second example: file sizes
A file size pipe shows how to handle numeric input and an optional precision parameter.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'fileSize', standalone: true })
export class FileSizePipe implements PipeTransform {
private static readonly units = ['B', 'KB', 'MB', 'GB', 'TB'];
transform(bytes: number | null | undefined, decimals = 1): string {
if (bytes == null || !Number.isFinite(bytes) || bytes < 0) {
return '';
}
let size = bytes;
let unit = 0;
while (size >= 1024 && unit < FileSizePipe.units.length - 1) {
size /= 1024;
unit++;
}
const text = unit === 0 ? String(size) : size.toFixed(decimals);
return `${text} ${FileSizePipe.units[unit]}`;
}
}In a template, {{ 1536 | fileSize }} shows 1.5 KB, and {{ 1536 | fileSize:3 }} shows 1.500 KB. A value in bytes is shown as a whole number, so {{ 512 | fileSize }} shows 512 B.
The guard clause rejects null, undefined, NaN, infinities, and negative numbers in one place. A pipe sits at the boundary between application data and the page, so it is the right place to decide how bad input is displayed.
Pure by default
By default a pipe is pure. Angular calls a pure pipe again only when its input values change, which means a changed primitive or a new object or array reference. If nothing changed, Angular reuses the previous result.
This makes pure pipes cheap, but it has a consequence for arrays and objects. A pure pipe does not see changes made inside the same array.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'activeOnly', standalone: true })
export class ActiveOnlyPipe implements PipeTransform {
transform(items: { name: string; active: boolean }[]): { name: string; active: boolean }[] {
return items.filter((item) => item.active);
}
}If a component calls this.users.push(newUser), the array reference stays the same. The pipe is not called again and the list does not update. Replacing the array fixes this:
this.users = [...this.users, newUser];The alternative is to mark the pipe pure: false, so Angular runs it on every change detection cycle. That is correct but runs far more often, and the next chapter covers when to choose it. For now, prefer immutable updates and keep your pipes pure.
Because a pure pipe may be called with the same input many times without running, its transform must be a pure function. It must return the same output for the same input and must not change anything outside itself. Do not read the current time, call a service that returns changing data, or modify the input.
Injecting services into a pipe
A pipe is created by Angular, so it can use dependency injection. Use inject() in a field initializer. This pipe formats a date with the application's current locale:
import { formatDate } from '@angular/common';
import { inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'shortTime', standalone: true })
export class ShortTimePipe implements PipeTransform {
private readonly locale = inject(LOCALE_ID);
transform(value: Date | string | number | null | undefined): string {
return value == null ? '' : formatDate(value, 'shortTime', this.locale);
}
}The locale is read once, when the pipe is created, so the pipe stays pure. If you inject a service whose data changes over time, the pipe becomes unsafe as a pure pipe, because its output no longer depends only on its inputs.
Common errors
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `No pipe found with name 'x'` | The pipe is missing from the component's `imports`, or the template name differs from the `name` in `@Pipe` | Add the class to `imports` and compare the two names | |
| The output does not update after `push` or a property change | A pure pipe received the same array or object reference | Replace the array or object instead of mutating it | |
| Runtime error on first render | `transform` assumes a value is present, but it is `null` before data loads | Accept `null | undefined` and return a fallback |
| A parameter has the wrong effect | Parameters are positional, so one was placed in the wrong slot | Check the order in `transform` or pass `undefined` for skipped ones | |
| Template type error on a parameter | Strict template checking found a type that does not match the `transform` signature | Change the argument or widen the parameter type |
Design guidance
- Use a pipe for display formatting that depends only on its inputs. Truncating text, formatting units, and showing initials all qualify.
- Do not use a pipe for filtering or sorting a large list on every change. Compute that in the component, for example when the data arrives, and keep the template simple.
- Name pipes with a lowercase first letter in camelCase, such as
fileSize. Name the class with aPipesuffix, such asFileSizePipe. - Keep one pipe to one job. Chain small pipes instead of building one with many options.
- Return a string from formatting pipes, so the result is always safe to interpolate.
Where pipe code is tested and called
A custom pipe is a plain class, so you can create it with new and call transform directly. Later chapters cover unit testing the pipe and calling pipes from component code. Keeping pipes free of hidden state is what makes both easy.
Exercise
A teammate writes a pure pipe sortByName that calls items.sort(...) and returns items. In the component, they add a new item with this.items.push(newItem). The list on the page does not update. Give two reasons the design is flawed, and describe a fix for each.
Show answer
First, the pipe is pure and push keeps the same array reference, so Angular sees no input change and does not call transform again. Fix this by replacing the array, for example this.items = [...this.items, newItem]. Second, sort() mutates the array it receives, so the pipe changes component state from the template. Fix this by sorting a copy: return [...items].sort((a, b) => a.name.localeCompare(b.name));.
Exercise
Using the truncate pipe from this chapter, write a template expression that shows description cut at 30 characters with the ending ..., then converts the result to upper case. Then explain what {{ description | truncate:null:'...' }} does to the limit.
Show answer
{{ description | truncate:30:'...' | uppercase }}. With null as the first parameter, the default of 20 does not apply, because defaults only apply to undefined. The limit is then null, and value.length > null compares against 0, so any non-empty text is cut to zero characters and replaced by the ellipsis. Pass undefined to keep the default.