What is the difference between Angular ngOnInit() and ngOnChanges()?

Chanaka Amarasinghe picture Chanaka Amarasinghe · Jun 8, 2018 · Viewed 10.5k times · Source

Angular provides lifecycle hook ngOnInit() and ngOnChanges() by default. Why should ngOnInit be used, if we already have a ngOnChanges? And constructor also.

Answer

Amit Chigadani picture Amit Chigadani · Jun 8, 2018

To keep it very short.

ngOnInit() is used to execute any piece of code for only one time (for eg : data fetch on load).

ngOnChanges() will execute on every @Input() property change.

If you want to execute any component method, based on the @Input() value change, then you should write such logic inside ngOnChanges().

As you claim why do we need ngOnInit() when we have ngOnChanges(), it is because you cannot execute one time code, on every @Input() property change. And you cannot use constructor as the replacement of ngOnInit() as well. Because the bindings, such as @Input properties are not available within the constructor.

I think you will get fair idea with this Diff between OnInit and constructor