What does ngOnChanges() do? When is it called?
In Angular, ngOnChanges() is a lifecycle hook that is called when a component's input properties (@Input) change.
Key points
- What it does:
- Lets you react to changes in data passed from the parent component.
- Receives a
changes: SimpleChangesobject, where you can see the old and new value of each changed property.
- When it is called:
- Before
ngOnInit()- the first time input property values are passed. - Every time the
@Inputvalues change after the component is initialized.
Example:
ts
export class ChildComponent implements OnChanges {
@Input() name: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Input data changed:', changes);
}
}- If
namechanges in the parent, Angular will callngOnChangesand show the old and new value.
In other words, ngOnChanges is a way to track and handle changes to a component's input data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.