Sub topic 3
Reacting to input changes with ngOnChanges
This chapter assumes you can write a basic Angular component, bind inputs from a parent template, and read simple TypeScript classes. It covers ngOnChanges, the hook Angular calls when a bound input changes. It also covers the SimpleChanges object that describes each change.
What ngOnChanges does
ngOnChanges runs whenever Angular sets one or more data-bound input properties on a component or directive. Angular calls it with a SimpleChanges object. That object lists only the inputs that changed during this pass.
The hook runs in two situations:
- Before
ngOnInit, on the first pass, when Angular sets the initial input values. - Again on every later change-detection pass in which at least one bound input has a new value.
If a component has no bound inputs, ngOnChanges never runs. It also does not run when you change an input from inside the component, for example this.userId = 'x'. Only bindings set by a parent trigger it.
The constructor cannot see inputs, because Angular creates the object before it assigns them. By the time ngOnChanges runs, the new values are already on the instance.
The SimpleChanges object
SimpleChanges is an object keyed by input property name. Each value is a SimpleChange with four members:
| Member | Meaning |
|---|---|
| `previousValue` | The value before this change. `undefined` on the first change. |
| `currentValue` | The new value. It is already assigned to the property. |
| `firstChange` | `true` when this is the first time the input was set. |
| `isFirstChange()` | A method that returns the same boolean as `firstChange`. |
Only changed inputs appear as keys. Always check for the key before you read it, as the example below does.
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 renders <app-user-card [userId]="id" /> and id starts as 'a1', the console shows this:
constructor: inputs are not set yet ''ngOnChanges undefined -> a1 first: truengOnInit: inputs are set a1
When the parent later sets id to 'b2', you see ngOnChanges a1 -> b2 first: false. ngOnInit does not run again, because it runs once per instance.
When Angular detects a change
Angular compares each bound input to its previous value with strict equality (===, more precisely Object.is). A new value triggers the hook. The same value does not.
This has a consequence for objects and arrays. If a parent mutates an object in place, the reference stays the same, so Angular sees no change and does not call ngOnChanges.
// Parent code
this.filter.status = 'done'; // same reference: no ngOnChanges in the child
this.filter = { ...this.filter, status: 'done' }; // new reference: ngOnChanges runsThis is the most common reason a developer reports that "ngOnChanges does not fire". The fix is to give the child a new reference, or to use ngDoCheck for in-place mutation (a later chapter covers it). Treating inputs as immutable also makes the component simpler to reason about.
Handling several inputs
Angular delivers all changed inputs from one pass in a single call. If a parent changes userId and mode in the same pass, you get one ngOnChanges call with both keys. Write the hook so each branch handles its own key, and avoid early returns that skip the other keys.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-report',
standalone: true,
template: `<p>{{ title }}</p>`,
})
export class ReportComponent implements OnChanges {
@Input() reportId = '';
@Input() locale = 'en';
title = '';
ngOnChanges(changes: SimpleChanges): void {
if (changes['reportId'] || changes['locale']) {
this.title = `Report ${this.reportId} (${this.locale})`;
}
if (changes['reportId'] && !changes['reportId'].firstChange) {
console.log('Report switched from', changes['reportId'].previousValue);
}
}
}The first branch recomputes derived state when either input changes. The second branch runs only for later changes, so it skips the initial assignment.
Typical uses
- Derive a value from inputs, such as the
titleabove. - Reset internal state when an identifier changes, for example clearing a form when
userIdchanges. - Start a request for new data when an input changes, and cancel the old one.
- Validate an input and log or throw on a bad value.
Keep the hook synchronous and cheap. It runs on the change-detection path, so slow work here slows rendering. Start asynchronous work from it, but do not wait inside it.
Gotchas and edge cases
Inputs set programmatically do not trigger it
Writing to an input from code does not call the hook. This applies to this.userId = 'x' inside the component. It also applies to componentRef.instance.userId = 'x' on a component you create dynamically. For dynamic components, call componentRef.setInput('userId', 'x'). That method records the change and runs ngOnChanges, and it marks the component for check when it uses OnPush.
Two-way binding
With [(value)], the parent updates the child's input when the child emits. The child's own ngOnChanges runs for that input after the parent assigns the value back. Do not emit another change from inside ngOnChanges for the same value. That causes loops or ExpressionChangedAfterItHasBeenChecked errors.
Setters as an alternative
For a single input, an input setter is shorter than ngOnChanges:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-badge',
standalone: true,
template: `<span>{{ label }}</span>`,
})
export class BadgeComponent {
label = '';
@Input() set name(value: string) {
this.label = value.trim().toUpperCase();
}
}A setter runs for that one input only. It has no previousValue and no firstChange. ngOnChanges is the better choice when several inputs interact or when you need the previous value.
Signal inputs
Components written with input() signal inputs do not receive ngOnChanges calls for those inputs. Use computed() for derived values and effect() for side effects instead. A later chapter covers them. Decorator-based @Input() properties still use ngOnChanges.
OnPush
With ChangeDetectionStrategy.OnPush, Angular checks the component only when an input reference changes, an event fires, or you mark it. ngOnChanges still runs on an input change. It is a reliable place to react to new references in an OnPush component.
Choosing between ngOnChanges and ngOnInit
| Need | Use |
|---|---|
| One-time setup that reads initial input values | `ngOnInit` |
| React to every later input change | `ngOnChanges` |
| Setup and reaction for the same input | `ngOnChanges`, with `firstChange` if the first pass differs |
| Mutation inside an object input | `ngDoCheck` |
Exercises
Exercise
A parent holds config = { theme: 'light' } and runs this.config.theme = 'dark' on a button click. The child has @Input() config and an ngOnChanges. Does the hook run, and how do you make it run?
Show answer
It does not run, because the object reference is unchanged and Angular compares by reference. Assign a new object, for example this.config = { ...this.config, theme: 'dark' }, so the binding sees a new reference and calls ngOnChanges.
Exercise
In ngOnChanges, you want to log "switched from X" only when userId changes after the initial binding. Which SimpleChange member do you check, and which value do you log?
Show answer
Check !changes['userId'].firstChange (or !changes['userId'].isFirstChange()), then log changes['userId'].previousValue.