What is ngOnChanges in Angular: Explained with Example
ngOnChanges is an Angular lifecycle hook method that runs whenever input properties of a component change. It lets you react to those changes by receiving a simple object describing what changed and how. This helps keep your component updated when its inputs update.How It Works
Imagine your component is like a mailbox that receives letters (input properties) from outside. Whenever a new letter arrives or an existing letter changes, ngOnChanges is called to let you know what changed.
This method receives a special object called SimpleChanges that tells you which inputs changed, their old values, and their new values. You can then use this information to update your component's behavior or appearance.
It runs before Angular updates the view, so you can prepare your component for the new data. This makes ngOnChanges very useful for reacting to input changes in a controlled way.
Example
This example shows a child component that receives a name input. Whenever name changes, ngOnChanges logs the old and new values.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-child', template: `<p>Hello, {{ name }}!</p>` }) export class ChildComponent implements OnChanges { @Input() name: string = ''; ngOnChanges(changes: SimpleChanges) { if (changes['name']) { const prev = changes['name'].previousValue; const curr = changes['name'].currentValue; console.log(`name changed from '${prev}' to '${curr}'`); } } } // Usage in parent component template: // <app-child [name]="parentName"></app-child>
When to Use
Use ngOnChanges when you want to respond to changes in input properties passed from a parent component. For example:
- Updating internal state based on new input values.
- Triggering side effects like fetching data when an input changes.
- Validating or transforming input data before rendering.
It is especially helpful when your component depends on inputs that can change over time, and you want to keep your component in sync without relying on user actions.
Key Points
- ngOnChanges runs every time an input property changes.
- It receives a
SimpleChangesobject with previous and current values. - It runs before Angular updates the view.
- It only works for properties decorated with
@Input(). - Use it to react and prepare your component for new input data.
Key Takeaways
ngOnChanges detects and reacts to changes in input properties.SimpleChanges object.@Input().