Sub topic 3
Reacting to input changes with ngOnChanges
This chapter assumes you can write a basic standalone component, bind inputs in a template, and know that ngOnInit exists. The earlier chapters cover those.
What ngOnChanges does
ngOnChanges is a hook that Angular calls whenever the value of a bound @Input() changes. It receives a SimpleChanges object that describes what changed. Use it when your component must do something in response to a new input value, such as reloading data or recalculating a derived value.
Angular calls it at two points:
- Before
ngOnInit, on the first binding, if the component has at least one bound input. - Again each time a bound input receives a new value from the parent's template.
Reading SimpleChanges
SimpleChanges is an object keyed by input property name. It contains only the inputs that changed in this pass. Each entry is a SimpleChange with three useful fields:
| Field | Meaning |
|---|---|
| `previousValue` | The value before this change. `undefined` on the first pass. |
| `currentValue` | The new value, already assigned to the property. |
| `firstChange` | `true` only for the first binding. |
import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `<p>User: {{ userId }}</p>`,
})
export class UserCardComponent implements OnChanges, OnInit, OnDestroy {
@Input() userId = '';
constructor() {
console.log('constructor: inputs are not set yet', this.userId);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['userId']) {
const change = changes['userId'];
console.log('ngOnChanges', change.previousValue, '->', change.currentValue, 'first:', change.firstChange);
}
}
ngOnInit(): void {
console.log('ngOnInit: inputs are set', this.userId);
}
ngOnDestroy(): void {
console.log('ngOnDestroy: release resources here');
}
}If a parent binds [userId]="'a1'" and later changes it to 'b2', the log shows the constructor with an empty value, then ngOnChanges -> a1 first: true, then ngOnInit. After the update it shows ngOnChanges a1 -> b2 first: false. The constructor does not run again, and neither does ngOnInit.
Always check for the specific key you care about. With several inputs, the hook runs once per pass with all changed inputs together, so changes['userId'] may be missing.
Common errors
- Mutating an object input. Angular compares input values by reference. If the parent changes
user.nameon the same object, no change is detected andngOnChangesdoes not run. Pass a new object instead, for exampleuser = { ...user, name: 'Ada' }. - Setting the property in code. Assigning
this.userId = 'x'inside the component, or from other code, never triggers the hook. Only template bindings do. The same applies to components you create dynamically and assign inputs to directly. - Expecting it without inputs. A component with no bound inputs never receives
ngOnChanges. - Heavy work on every pass. The hook can run often. Keep it cheap, and compare
currentValuewithpreviousValuebefore starting anything expensive. - Changing the same input inside the hook. Overwriting an input from within
ngOnChangescan cause confusing state, because the parent still holds the original value.
Exercise
A parent holds config = { theme: 'dark' } and passes it to a child with [config]="config". The parent later runs this.config.theme = 'light'. Does the child's ngOnChanges run, and how would you make it run?
Show answer
It does not run, because the object reference is unchanged and Angular compares inputs by reference. Assign a new object in the parent, for example this.config = { ...this.config, theme: 'light' }. The child's ngOnChanges then receives a config entry with the old and new objects.