ngOnChanges: Reacting to Input Property Changes

The `ngOnChanges` hook is a property watcher for child components, firing when a parent changes an `@Input()` value. It's used to trigger logic when specific data changes.
WHY IT EXISTS Components often need to know when data passed to them from a parent has changed. Instead of manually checking on every render cycle, Angular provides a dedicated hook to be notified automatically, enabling reactive behavior without performance overhead.
THE MENTAL MODEL Think of ngOnChanges as a delivery notification for your component's inputs. When a parent component sends a new "package" (a new value for an @Input()), this hook is the doorbell that rings, handing you a receipt that shows exactly what arrived and what it replaced.
HOW IT WORKS To use it, you implement the OnChanges interface on your component class. This requires you to define an ngOnChanges method that accepts one argument: an object of type SimpleChanges. This object acts as a map where the keys are the names of the input properties that have changed. The value for each key is a SimpleChange object, which contains the property's previousValue and currentValue. This hook fires before ngOnInit on the first run and then for every subsequent change to an input property's reference.
WHEN TO USE IT Use ngOnChanges when a component's logic depends on the combination of several inputs, or when you need to compare an input's previous and current value. It's perfect for triggering side effects, like making an API call when a userId input changes, because you can verify the ID actually changed before re-fetching data.
WHEN NOT TO USE IT Avoid ngOnChanges for reacting to a single input's change; a property setter (set myInput(value: any) { ... }) is often cleaner. The biggest footgun is that it does NOT detect mutations inside an object or array. If you change a property on an object passed as an input (e.g., user.name = 'new'), ngOnChanges will not fire because the object reference itself has not changed. For that, you must either pass a new object or use a different change detection strategy.
ONE CANONICAL EXAMPLE A UserProfileComponent receives a userId via an input. When a parent component switches the selected user, the userId input is updated. The ngOnChanges hook detects this. Inside the hook, you can check if (changes.userId && !changes.userId.isFirstChange()) to run logic only on subsequent updates, then trigger a service to fetch the profile for the new userId. This ensures the component's data stays in sync with its inputs.
Read the original → angular.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.