Sub topic 4
Input changes are reference checks: immutable updates
This chapter assumes you can build components with @Input bindings, know how to enable ChangeDetectionStrategy.OnPush on a component, and understand that JavaScript objects and arrays are passed by reference. The chapter explains how Angular decides that an input has changed. It also shows how to write updates that always pass that decision.
What Angular compares
When Angular checks a parent's template, it evaluates each input binding, such as [user]="user". It compares the new value with the value it stored from the previous check. The comparison is Object.is, which behaves like === with two differences: NaN equals NaN, and +0 does not equal -0.
- For primitives (
string,number,boolean,null,undefined), the comparison looks at the value.'Ada'and'Ada'are equal. - For objects and arrays, the comparison looks at the reference. Two objects with identical contents are different if they are different objects. One object whose contents changed is still the same object.
If the values differ, Angular writes the new value to the child's input and marks the child as needing a check. If the values are equal, Angular does nothing for that input. Under OnPush, a child with no changed inputs and no other trigger is skipped, along with its whole subtree.
Angular never looks inside an object to see whether a property changed. Doing so would mean walking every input on every check, which is the cost OnPush exists to avoid.
Why mutation leaves the view stale
This is the pair of components from the spine. The child opts into OnPush:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
export interface User {
name: string;
}
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user.name }}</p>`,
})
export class UserCardComponent {
@Input({ required: true }) user!: User;
}The parent offers both ways of changing the data:
import { Component } from '@angular/core';
import { User, UserCardComponent } from './user-card.component';
@Component({
selector: 'app-parent',
imports: [UserCardComponent],
template: `
<app-user-card [user]="user" />
<button (click)="renameByMutation()">Mutate</button>
<button (click)="renameImmutably()">Replace</button>
`,
})
export class ParentComponent {
user: User = { name: 'Ada' };
renameByMutation() {
// Same object reference: the OnPush child does not update.
this.user.name = 'Grace';
}
renameImmutably() {
// New reference: the OnPush child is checked and shows the new name.
this.user = { ...this.user, name: 'Grace' };
}
}After renameByMutation(), the parent's data is correct, because user.name is 'Grace'. The child's <p> still shows Ada. The binding [user]="user" evaluated to the same object as before, so Object.is returned true and the child was never marked dirty.
After renameImmutably(), the spread creates a new object. The binding now evaluates to a different reference, and the child refreshes.
The mutation bug can also hide itself. If something else marks the child dirty later, such as a click handler inside the child, the child re-renders and suddenly shows Grace. A view that is stale and then fixes itself at an unrelated moment is a typical sign of mutated input data.
Immutable update patterns
An immutable update never changes an existing object or array. It builds a new one that contains the change. The following table maps common mutating operations to replacements.
| Goal | Mutates (avoid for OnPush inputs) | Replaces (use) |
|---|---|---|
| Set a property | `user.name = 'Grace'` | `user = { ...user, name: 'Grace' }` |
| Append to an array | `items.push(x)` | `items = [...items, x]` |
| Remove from an array | `items.splice(i, 1)` | `items = items.filter((it) => it.id !== id)` |
| Replace one element | `items[i] = x` | `items = items.map((it) => (it.id === id ? x : it))` |
| Sort | `items.sort(cmp)` | `items = [...items].sort(cmp)` or `items.toSorted(cmp)` |
| Reverse | `items.reverse()` | `items = [...items].reverse()` or `items.toReversed()` |
toSorted, toReversed, and with are ES2023 methods. Your TypeScript lib setting must include them, and your target browsers must support them. The spread-then-mutate form works everywhere. It is safe because the mutation applies to a fresh copy that nobody else holds yet.
A complete array example
The child displays a list and receives it as a read-only array:
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.title }} @if (todo.done) { (done) }</li>
}
</ul>
`,
})
export class TodoListComponent {
@Input({ required: true }) todos!: readonly Todo[];
}The parent updates the list only by replacing it:
import { Component } from '@angular/core';
import { Todo, TodoListComponent } from './todo-list.component';
@Component({
selector: 'app-todos',
imports: [TodoListComponent],
template: `
<app-todo-list [todos]="todos" />
<button (click)="add()">Add</button>
<button (click)="toggleFirst()">Toggle first</button>
<button (click)="removeFirst()">Remove first</button>
`,
})
export class TodosComponent {
private nextId = 3;
todos: readonly Todo[] = [
{ id: 1, title: 'Read docs', done: false },
{ id: 2, title: 'Write tests', done: false },
];
add() {
this.todos = [...this.todos, { id: this.nextId++, title: 'New task', done: false }];
}
toggleFirst() {
const firstId = this.todos[0]?.id;
this.todos = this.todos.map((t) => (t.id === firstId ? { ...t, done: !t.done } : t));
}
removeFirst() {
this.todos = this.todos.slice(1);
}
}toggleFirst() shows the usual pattern for one element. map returns a new array, and only the matching element is copied. The other elements keep their references. That detail matters in the next section.
Structural sharing and nested data
An immutable update does not mean a deep copy. You copy only the objects on the path from the root to the changed value. Everything else is reused. This is called structural sharing.
interface Address {
city: string;
street: string;
}
interface Profile {
name: string;
address: Address;
tags: readonly string[];
}
const before: Profile = {
name: 'Ada',
address: { city: 'London', street: 'Main St' },
tags: ['admin'],
};
const after: Profile = {
...before,
address: { ...before.address, city: 'Paris' },
};
console.log(after === before); // false
console.log(after.address === before.address); // false
console.log(after.tags === before.tags); // trueThe root and address get new references because they sit on the path to city. The tags array is untouched, so a child component bound to profile.tags sees an identical reference and is not refreshed. With a deep copy, such as structuredClone(before), every nested reference would change. Every OnPush child would then be marked dirty on every update, and you would lose most of the benefit of the strategy.
Remember that a binding is checked at the level you bind. If a child takes [address]="profile.address", it refreshes when address is replaced. If a child takes [profile]="profile", replacing only address still refreshes it, because the root changed too.
Letting the compiler catch mutations
Mutation bugs are silent at runtime, so it helps to make them compile errors. Declare inputs and state with read-only types:
interface Settings {
readonly theme: 'light' | 'dark';
readonly pageSize: number;
}
function toggleTheme(settings: Settings): Settings {
// settings.theme = 'dark'; // error TS2540: Cannot assign to 'theme'
return { ...settings, theme: settings.theme === 'light' ? 'dark' : 'light' };
}readonly properties, Readonly<T>, and readonly T[] (or ReadonlyArray<T>) stop assignment, push, and splice in typed code. Object.freeze adds a runtime guard. In strict mode, frozen objects throw a TypeError on write, so the bug appears at the exact line that mutates. Freezing is shallow, so it protects only the top level of an object. Use it in development builds or tests if you are concerned about its cost.
Common errors
Mutating after the first binding
This is the bug above: this.items.push(x) followed by no reassignment. The fix is to assign a new array to the field that is bound.
Creating a new reference on every check
The opposite problem also exists. A binding such as this one produces a new array every time the parent's template runs:
import { Component } from '@angular/core';
import { Todo, TodoListComponent } from './todo-list.component';
@Component({
selector: 'app-open-todos',
imports: [TodoListComponent],
template: `<app-todo-list [todos]="todos.filter(openOnly)" />`,
})
export class OpenTodosComponent {
todos: readonly Todo[] = [{ id: 1, title: 'Ship', done: false }];
openOnly = (t: Todo) => !t.done;
}filter returns a new array on every evaluation, so Object.is never matches. The OnPush child is marked dirty on every parent check, and it also receives a changed input each time. The view is correct but the optimization is lost. Compute the derived value once when its source changes, store it in a field, or use a pure pipe or a computed signal. Then the reference changes only when the data does.
Copying without reassigning
const copy = [...this.todos]; copy.push(x); builds a new array, but if you never assign it to the bound field, the binding still holds the old one. The copy has to become the value that the template reads.
Mutating inside a service and sharing the object
If a service holds an object and several components read it, one component that mutates it can change what the others hold, with no input change for any OnPush component to notice. Treat shared state as immutable everywhere. Publish a new object from the service whenever it changes.
Assuming a new object is always a cheap change
Replacing the reference tells Angular to re-check the child. It does not tell Angular what changed inside. The child's template then re-evaluates all of its bindings. For very large lists, add track in @for with a stable key so Angular reuses DOM nodes for unchanged items. Because map preserves the references of unchanged elements, this works well alongside immutable updates.
Inputs, `ngOnChanges`, and signal inputs
Angular calls ngOnChanges only for inputs whose reference changed, using the same comparison. A mutation therefore produces no ngOnChanges call, in any change detection strategy. Code that reacts to input changes in that hook depends on immutable updates as much as the view does.
Signal-based inputs, declared with input(), follow the same rule. The signal's value is replaced when the binding's reference changes, and computed signals that depend on it are re-evaluated only then. Mutating an object that a signal holds does not notify anything that reads the signal.
Summary
- Angular compares input values with
Object.is. Primitives compare by value. Objects and arrays compare by reference. - A mutated object keeps its reference, so an
OnPushchild bound to it is not marked dirty and shows stale data. - Update by replacing: object spread, array spread,
map,filter,slice, and the ES2023 copying methods. - Copy only the path to the changed value. Structural sharing keeps unchanged subtrees from refreshing.
- Avoid creating new references inside template expressions, because that marks the child dirty on every check.
- Use
readonlytypes to turn mutation bugs into compile errors.
Exercise
A parent holds todos: Todo[] and passes it to an OnPush child with [todos]="todos". A button handler runs this.todos.push(newTodo), and the child does not show the new item. Write the handler so the child updates, and explain why your version works while push does not.
Show answer
Use this.todos = [...this.todos, newTodo];. Angular compares the new binding value with the previous one using Object.is. push changes the existing array, so the reference is identical and the OnPush child is not marked for checking. The spread creates a new array, so the reference differs and the child is marked dirty and re-rendered. Declaring the field as readonly Todo[] would also make the push version fail to compile.
Exercise
Given const a = { name: 'Ada', address: { city: 'London' }, tags: ['x'] }; you run const b = { ...a, address: { ...a.address, city: 'Paris' } };. Which of these are true: b === a, b.address === a.address, b.tags === a.tags? Which OnPush children, bound to profile, profile.address, and profile.tags, would be refreshed if profile changed from a to b?
Show answer
Only b.tags === a.tags is true. The root and address were copied, and tags was reused. The children bound to profile and profile.address receive new references and are refreshed. The child bound to profile.tags receives the same array and is not refreshed by this input change.