Difference between the constructor and ngOnInit in Angular2


I have been looking at the documentation of angular 2 about the Lifecycle but it is not clear to me.

What is the difference between the constructor and ngOnInit?

asked by Holmio 13.10.2016 в 09:47

1 answer


The constructor is used for lighter tasks.

ngOnInit is a special hook intended for more "heavy" tasks, like bringing the provider's data or things like that. Angular recommends leaving builders for very light tasks, and the rest leave it for ngOnInit.

ngOnInit will be invoked only once (it is assumed that after the first onChanges, but in practice it is called in the creation of the element, as if the constructor were invoked in the creation of the class).

Here link explain it a bit more in detail (in " The ngOnInit Lifecycle Hook ")

Regarding the other hooks, onchanges and ondestroy do not have much science and are more or less self-explanatory. The rest is detailed in link

answered by 13.10.2016 / 10:13