Sub topic 11
Pure versus impure pipes
This chapter assumes you can write a standalone Angular component, use template interpolation, and have read the previous chapter on writing a custom pipe with @Pipe and PipeTransform. Here you will learn when Angular runs a pipe, why that matters for arrays and objects, and how to choose between a pure and an impure pipe.
What "pure" means for a pipe
A pipe is pure when its output depends only on its inputs. Angular takes advantage of this. It runs a pure pipe's transform method again only when one of its inputs has changed.
Every pipe is pure by default. The pure option of @Pipe defaults to true, so you get this behavior without writing anything extra.
"Changed" has a specific meaning. For a pure pipe, Angular detects a change in either of two ways:
- A primitive input (string, number, boolean) has a different value.
- An object input (including an array, a
Date, or any other object) has a different reference. In other words, it is a different object in memory, not the same object with different contents.
Angular compares with identity (===) and does not inspect the contents. When nothing has changed, it reuses the previous result and skips the call to transform.
Why Angular does this
Angular checks every template binding during change detection. Change detection runs after events such as clicks, timers and HTTP responses, so in a busy application it runs often. If every pipe ran on every pass, a filter or sort over a large list would repeat constantly, even when the list had not changed.
A pure pipe avoids that cost. With identity checks, the pipe runs once for a given input and the result is reused until the input changes.
The common error: mutating an array
The same shortcut causes the most common pipe bug. Consider the activeOnly pipe from the topic's examples, written here as a pure pipe, which is the default:
import { Pipe, PipeTransform } from '@angular/core';
export interface Task {
name: string;
active: boolean;
}
@Pipe({ name: 'activeOnly', standalone: true })
export class ActiveOnlyPipe implements PipeTransform {
transform(items: Task[]): Task[] {
console.log('activeOnly ran');
return items.filter((item) => item.active);
}
}Now use it in a component that adds tasks by mutating the array:
import { Component } from '@angular/core';
import { ActiveOnlyPipe, Task } from './active-only.pipe';
@Component({
selector: 'app-task-list',
standalone: true,
imports: [ActiveOnlyPipe],
template: `
<button (click)="addMutating()">Add (push)</button>
<button (click)="addImmutably()">Add (new array)</button>
<ul>
@for (task of tasks | activeOnly; track task.name) {
<li>{{ task.name }}</li>
}
</ul>
`,
})
export class TaskListComponent {
tasks: Task[] = [{ name: 'Write chapter', active: true }];
private counter = 0;
addMutating(): void {
this.tasks.push({ name: `Pushed ${++this.counter}`, active: true });
}
addImmutably(): void {
this.tasks = [...this.tasks, { name: `Copied ${++this.counter}`, active: true }];
}
}Clicking Add (push) does nothing visible. push changes the array's contents, but this.tasks still points to the same array object. The pure pipe sees the same reference as before, so it returns its cached result, and the list stays the same.
Clicking Add (new array) works. The spread syntax builds a new array, so the reference changes and Angular runs transform again. After that click, the console prints activeOnly ran, and the new item appears. It also includes the earlier pushed items, because they were in the array when it was copied.
The same problem appears when you change a property of an object that is passed to a pure pipe, for example user.name = 'Ada' when the pipe receives user.
The same caching can also work against you in the other direction: a pure pipe is allowed to return stale data only if its inputs did not change, so a pipe that reads outside data, such as the current time, will not update on its own.
Two ways to fix it
When a pure pipe does not update, you have two options. They have different costs.
Option 1: keep the pipe pure and use immutable updates
Replace the array or object instead of changing it. Use [...items, newItem] to add, items.filter(...) to remove, and items.map(...) to change an element. Each produces a new reference.
This is the preferred approach. The pipe stays fast, and the code also works well with other features that depend on reference changes, such as OnPush change detection and signals.
Option 2: make the pipe impure
Set pure: false:
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);
}
}An impure pipe runs on every change detection cycle, whether or not its inputs changed. With this version, push works, because transform runs again on the next cycle and sees the new contents.
The cost is that transform now runs after every click, keystroke, timer tick and HTTP response anywhere in the component tree that triggers change detection. For a small list this is harmless. For a large list or an expensive computation, it can make the interface slow.
Comparing the two
| Row | Pure pipe | Impure pipe |
|---|---|---|
| Declared with | `pure: true` (default) | `pure: false` |
| Runs when | An input value or reference changes | Every change detection cycle |
| Sees in-place mutation | No | Yes |
| Performance | Cheap | Cost grows with the work in `transform` |
| Returns new object each run | Safe | Can cause extra work downstream |
| Typical use | Formatting, conversion | Reading changing outside state, `async` |
A subtle trap: impure pipes that return new objects
An impure pipe that returns a new array each time, as filter does, hands the template a different reference on every cycle. This is usually fine for @for, because track lets Angular match items by identity. It can be a problem if you pass the result to a child component input. The child sees a new array on every cycle and may re-render or re-run its own pure pipes.
If you must use an impure pipe, keep it cheap, and consider caching the last input and result inside the pipe so it returns the same reference when nothing has really changed.
Built-in pipes and purity
Most built-in pipes are pure: date, currency, number, percent, uppercase, lowercase, titlecase, slice and json (despite its debugging role, it is pure in Angular's current implementations, but check the API reference for your version if it matters). Two behave differently:
asyncis impure. It has to be, because the Observable or Promise it watches can emit at any time, and the pipe has to report the latest value each cycle. It manages its own subscription and marks the component for a check when a new value arrives.keyvalueis a special case. It is impure internally in the sense that it checks whether the object's keys or values changed, so it can detect in-place changes to the object. It returns the same array when nothing changed, so it avoids the problem described above.
Because date is pure, the following displays a stale value if the underlying Date object is mutated with setDate:
<p>{{ due | date:'mediumDate' }}</p>If due is a Date and you call this.due.setDate(20), the reference is the same and the pipe does not rerun. Assign a new Date instead: this.due = new Date(2026, 10, 20).
Choosing between them
Work through these questions in order:
- Can the data be updated immutably? If yes, use a pure pipe. This is the default choice.
- Does the output depend on something other than the pipe's inputs, such as the current time, a service, or a mutable global? Then a pure pipe cannot be correct. Consider whether a computed value in the component would be clearer than a pipe.
- Do you really need to react to in-place changes, and is the work in
transformcheap? Then an impure pipe is acceptable. - Is the work expensive and the data mutable? Move the computation into the component, for example into a signal
computed, and avoid the pipe.
Checking when your pipe runs
To see how often transform is called, add a temporary console.log inside it and interact with the page. With a pure pipe, the log appears once per distinct input. With an impure pipe, it appears after almost every event, including ones unrelated to the pipe. Remove the log afterward.
Exercise
A component holds items = [{ id: 1, done: false }] and the template shows {{ items | doneCount }}, where doneCount is a pure pipe that counts items with done === true. A button handler runs this.items[0].done = true, but the displayed count stays at 0. Why, and what are two ways to fix it?
Show answer
The handler changes a property of an object inside the array, so items is still the same reference. A pure pipe re-runs only when its input value or reference changes, so it returns the cached result. Fix 1 (preferred): update immutably, for example this.items = this.items.map(i => i.id === 1 ? { ...i, done: true } : i), which gives the pipe a new array. Fix 2: declare the pipe with pure: false so it runs on every change detection cycle, accepting the extra cost.
Exercise
Why is the built-in async pipe impure, and what does that tell you about when impure pipes are appropriate?
Show answer
The value it displays comes from an Observable or Promise that can emit at any time, which is state outside its input reference. A pure pipe would never refresh when the same Observable emits a new value. The async pipe is appropriate as impure because it does very little work per cycle: it returns its stored latest value. Impure pipes fit cases where the output depends on outside state and each run is cheap.