Now that the meaning of both Constructor and ngOnInit is clear, it will be easy to evaluate the difference between constructor and ngOnInit. Starting with the basics, the main role of ngOnInit is to provide a signal that Angular has done initializing the component and that users can roll on further. The constructor, on the other hand, is significantly used to initialize the class members but it is unable to perform the whole work. It is only beneficial in the case of dependency injection and initialization of the class field. That being said, the compiler should actually avoid writing the work on Constructor. ngOnInit is a better place to write work code that is required at the time of class instantiation.
What Should Go into Constructor vs NgOnlnit?
Other than their usage, are you wondering what should go into constructor vs ngOnInit? The essential difference between the constructor and ngOnInit can be learned by taking into consideration the following attributes.
JS/TS Language
ngOnInit Angular is just a method in the class. It is directly associated with Angular development and is no different from any other method in the class. It is upto the compiler if he wants to implement the method into the class or not. Constructor, on the other hand, is required to be implemented, no matter what. Compiler especially calls it during the creation of a class instance because it can easily transpile JavaScript constructor functions. Thus, in the contrast between typescript constructor vs ngOnInit, the constructor is considered as regardless, no matter if one implements it in the class or not.
Component Initialization Process
Taking in the perspective of the component initialization process, there is a massive difference between the ngOnInit vs constructor. To grasp the comparison, it is important to know that Angular bootstrap comprises two significant steps, that is, the construction of component tree and running change detection. Angular constructor is called when the developer has to construct the component tree. On the flip side, Angular ngOnInit can be a support system in the following change detection phase, when called. Thus it would not be wrong to say that both constructor and ngOnInit help in bootstrapping the application.
Check out the table below to conclude the notion of angular constructor vs ngOnInit.
ngOnInit | Angular |
It is a lifecycle hook method in Angular | It is not directly associated with Angular and is actually a TypeScript feature |
It is called when the component is initialized | It is called at the time of creating the class’ object |
It is a place to write the code that needs to be executed as soon as class is instantiated | It initializes the class members |
It is used to perform actually business logic | It is used in the case of dependency injections |
In ngOnInit Angular, everything is often ready at the time of invocation | In Angular Constructor, every component is not initialized at the time of invocation |