Sub topic 4
Input changes are reference checks: immutable updates
This chapter assumes you can build components with templates and bindings, pass data through @Input, and tell an object reference from a copy in JavaScript. It also assumes you know what ChangeDetectionStrategy.OnPush does at a basic level, from the previous chapter.
What Angular compares
When a parent re-renders, Angular looks at each binding such as [user]="user". For an OnPush child, it compares the new value to the previous value with Object.is, which behaves like === for objects. It does not look inside the object.
- If the two values are the same reference, the input has not changed. Angular skips the child.
- If they are different references, the input has changed. Angular marks the child for checking and updates its bindings.
For primitives such as strings, numbers, and booleans, comparing by reference is the same as comparing by value. The trouble starts only with objects and arrays.
A child that depends on its input
The child below uses OnPush and reads one property of its input.
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;
}Mutation leaves the child stale
The parent offers two ways to rename the user. One mutates the object. The other replaces it.
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' };
}
}Click Mutate and the card still shows "Ada". The click is an event in the parent, so the parent is checked. But this.user still points to the same object, so the binding comparison finds no change and the child is skipped. The data did change. The view did not.
Click Replace and the spread syntax builds a new object. The reference differs, so Angular checks the child and it shows "Grace".
If you mutate and then also replace, the child updates, but only because of the replacement. The mutation had no part in it.
Immutable update patterns
An immutable update never changes the existing object or array. It builds a new one that shares the unchanged parts. These are the patterns you will use most.
| Change | Mutating (avoid for OnPush inputs) | Immutable replacement |
|---|---|---|
| Set a property | `user.name = 'Grace'` | `user = { ...user, name: 'Grace' }` |
| Add to an array | `items.push(item)` | `items = [...items, item]` |
| Remove from an array | `items.splice(i, 1)` | `items = items.filter((x) => x.id !== id)` |
| Update one element | `items[i].done = true` | `items = items.map((x) => x.id === id ? { ...x, done: true } : x)` |
| Sort an array | `items.sort(...)` | `items = [...items].sort(...)` |
The spread operator makes only a shallow copy. For nested data, copy each level that you change:
interface Address {
city: string;
}
interface Profile {
name: string;
address: Address;
}
function moveTo(profile: Profile, city: string): Profile {
return {
...profile,
address: { ...profile.address, city },
};
}Here the outer object and the address object are both new. If you wrote { ...profile } and then set profile.address.city, the nested object would be shared with the old value, and a child that reads address as its own input would not see a new reference.
Where the bug hides
Stale views from mutation are easy to miss for three reasons.
- The data is correct. A breakpoint or
console.logshows the new value, so the bug looks like a rendering problem. - A different trigger can hide it. If an event fires inside the child, or the child is checked for another reason, the view catches up and the bug seems to come and go.
- Mutation works under the default strategy. Code that was fine before switching a component to OnPush can break only after the switch.
When you see a stale child, check how the data reaches it. Search the code that produces the input for in-place writes such as property assignments, push, and splice.
Exercise
A parent holds todos: Todo[] and binds it to an OnPush child with [todos]="todos". A button handler runs this.todos.push(newTodo), and the child's list does not grow. Why, and what is the smallest fix?
Show answer
push changes the array in place, so the binding still holds the same array reference. Angular compares by reference, sees no change, and skips the OnPush child. The fix is to assign a new array: this.todos = [...this.todos, newTodo];.