Sub topic 7
Immutable updates and input reference checks
This chapter assumes you know how an OnPush component decides whether to be checked (covered in the previous chapter), and that you are comfortable with component inputs, template bindings and the spread operator. Here you will look at the check that decides whether an OnPush child sees new data from its parent, and how to write code that passes it.
What Angular compares on an input binding
When Angular checks a parent's template, it evaluates each binding expression and compares the result with the value it stored on the previous pass. For a binding such as [user]="user", the comparison is Object.is(previous, current). This is a reference check for objects and arrays, and a value check for primitives.
- If the two values are identical, Angular does nothing for that binding.
- If they differ, Angular writes the new value to the child's input. This also marks an OnPush child as dirty, so the child is checked in this pass.
The comparison is shallow. Angular never looks inside the object, so it cannot know that user.name changed while user stayed the same object. A Default component hides this because it is checked on every cycle anyway. An OnPush component does not, so its input must change by reference whenever its contents change.
Object.is differs from === in two edge cases. NaN is equal to itself, so a binding that stays NaN does not count as a change. +0 and -0 are different values, so a binding that flips between them does count as a change.
The mutation trap
Compare two ways of adding an item to a list shown by an OnPush child.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
export interface Todo {
id: number;
title: string;
done: boolean;
}
@Component({
selector: 'app-todo-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (todo of todos(); track todo.id) {
<li>{{ todo.done ? '[x]' : '[ ]' }} {{ todo.title }}</li>
}
</ul>
`,
})
export class TodoList {
todos = input.required<Todo[]>();
}import { Component } from '@angular/core';
import { Todo, TodoList } from './todo-list';
@Component({
selector: 'app-todo-page',
imports: [TodoList],
template: `
<app-todo-list [todos]="todos" />
<button (click)="addByPush()">Add (push)</button>
<button (click)="add()">Add (new array)</button>
<button (click)="toggle(1)">Toggle first</button>
`,
})
export class TodoPage {
todos: Todo[] = [
{ id: 1, title: 'Write chapter', done: false },
{ id: 2, title: 'Review chapter', done: false },
];
private nextId = 3;
addByPush() {
// Same array reference: the OnPush child is not marked dirty.
this.todos.push({ id: this.nextId++, title: 'Pushed', done: false });
}
add() {
// New array reference: the child's input changes, so it is checked.
this.todos = [...this.todos, { id: this.nextId++, title: 'Added', done: false }];
}
toggle(id: number) {
// New array and a new object for the changed item only.
this.todos = this.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
}
}The click handler runs, so Angular checks the parent. The parent's binding still holds the same array, so the child receives no new input and is skipped. The array has grown, but the screen has not.
The new item appears later, on the next click of "Add (new array)" or "Toggle first". Those handlers create a new array that already contains the pushed item. This delayed update is a common symptom: the data is correct, and the view lags behind until an unrelated change forces a new reference.
Writing immutable updates
An immutable update leaves the old object untouched and builds a new one for the part that changed. The table lists common mutating operations and their non-mutating replacements.
| Goal | Mutates in place | Returns a new value |
|---|---|---|
| Add to an array | `items.push(x)` | `[...items, x]` |
| Remove from an array | `items.splice(i, 1)` | `items.filter((_, j) => j !== i)` |
| Replace one element | `items[i] = x` | `items.map((v, j) => (j === i ? x : v))` or `items.with(i, x)` |
| Sort | `items.sort(cmp)` | `items.toSorted(cmp)` or `[...items].sort(cmp)` |
| Reverse | `items.reverse()` | `items.toReversed()` |
| Change a property | `obj.name = 'x'` | `{ ...obj, name: 'x' }` |
| Delete a property | `delete obj.name` | `const { name, ...rest } = obj` |
with, toSorted and toReversed come from ES2023. Check that your TypeScript lib setting and your target browsers support them. If they are not available, copy first and then mutate the copy.
Nested data
A spread copy is shallow. To change a deeply nested value, copy every object along the path from the root to the change, and reuse everything else.
interface Address {
city: string;
zip: string;
}
interface Customer {
name: string;
address: Address;
tags: string[];
}
function moveCustomer(customer: Customer, city: string): Customer {
return {
...customer,
address: { ...customer.address, city }, // new Address
// tags is reused: same reference as before
};
}The result is a new Customer and a new Address, but the same tags array. Reusing untouched branches is called structural sharing. A child that binds only to customer.tags sees an unchanged reference and is not checked, so one update stays cheap even when the root object is replaced.
If you do { ...customer } and then assign copy.address.city = 'x', you have changed the original Address too. The new Customer exists, but the old and new objects share that mutated address, so any child bound to customer.address sees no change.
Edge cases
- Class instances. Spreading a class instance copies its own properties but not its prototype, so methods are lost. Build the replacement with a constructor or a
with-style method that returns a new instance. - Map and Set. Calling
setoraddmutates in place. Create a new one withnew Map(old)ornew Set(old)and then change the copy. - Dates.
date.setDate(...)mutates. Create a newDateinstead. structuredClone. It makes a deep copy, which gives every nested object a new reference. Every OnPush child below the root then sees a change, and you pay for the copy itself. Prefer targeted spreads.- Events in the child itself. A DOM event handled in an OnPush component's own template marks that component and its ancestors dirty. Mutating the component's own state inside that handler therefore appears to work. This hides the bug until the same data arrives through an input.
- Mutation by a service. If a service mutates an object that components hold by reference, no binding sees a new reference. Have the service replace the object, or expose it through a signal or observable.
Keeping lists efficient
A new array reference forces the child to re-run its template. In an @for block, the track expression then decides how much DOM work follows. With track todo.id, Angular matches old and new items by id, reuses the existing elements and updates only the bindings that changed. Tracking by identity (track $index or the object itself) after a map that creates new objects causes more DOM to be recreated. Use a stable key such as an id.
Catching accidental mutation
In development, Object.freeze makes mutation fail loudly. In strict mode, writing to a frozen object throws a TypeError. Freezing is shallow, so apply it at each level you care about, or use a readonly type to have the compiler reject mutations.
interface Settings {
readonly theme: string;
readonly tags: readonly string[];
}
const settings: Settings = Object.freeze({
theme: 'dark',
tags: Object.freeze(['a', 'b']),
});
// settings.theme = 'light'; // compile error: read-only property
// settings.tags.push('c'); // compile error: no push on readonly arrayTyping inputs as readonly Todo[] documents that the child must not modify what it receives.
Exercise
A parent holds filters = { tags: ['a'], active: true } and binds [filters]="filters" to an OnPush child. Its handler runs this.filters.tags.push('b') and the child does not update. Write a replacement for the handler body that makes the child update without copying tags more than needed, and say why it works.
Show answer
this.filters = { ...this.filters, tags: [...this.filters.tags, 'b'] };. The binding now evaluates to a new object, so Object.is reports a difference, the child's input is written and the child is marked dirty. Only filters and tags are copied. Any other properties are reused from the old object.
Exercise
Why does an OnPush list sometimes show an item added with push only after the user clicks an unrelated button that creates a new array?
Show answer
The push does not change the array reference, so the child is skipped. The later action replaces the array with a copy of the current contents, and that copy includes the pushed item. The child sees a new reference and renders the whole list, including the earlier item.