Angular provides lifecycle hook ngOnInit() and ngOnChanges() by default. Why should ngOnInit be used, if we already have a ngOnChanges? And constructor also.
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