Difference Between Constructor And ngOnInit In Angular4
Posted By : Mahima Gautam | 24-Jun-2018
This constructor used on the ES6 classes ie typescript are itself a feature of the class, rather than angular features. It is basically out of the angular control when it is invoked. Constructors are default methods of classes that get executed when the class is instantiated and it ensures the proper initialization of the fields in class and subclasses. The constructor is initialized by javascript engines and typescript allows what all dependencies are required to map specific property.
For ngOnInit, it is very important to note that these javascript engines call the constructor, not the angular directly by which the ngOnInit lifecycle hook is created. By adding this, angular fires the method once it finishes setting the component up. ngOnInint tells that angular has finished its initialization of component. These phases contain first pass at the detection of the change that occurs against those properties that might bind themselves to the component itself - like using @input() decorator. Because of this these properties are present inside ngOnInit and are undefined in the constructor by the design.
Constructor versus ngOnInit
With an example of using services, we will try to understand the difference between constructor and ngOnInint. For eg:- You want some data from the server when the component gets activated and want some additional processing on the data received from the server. It's easy to do that with ngOnInit over the constructor And limits the callbacks layers we need to add to the application.
For usingOnInit function, we need to import it
import {Component, OnInit} from '@angular/core';
and then use the method
export class HomeComponent implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
Now implement the interface for executing customized initialize logic just after the directive data-bound properties have been initialized. It is called just after data-bound directives properties. It is invoked once when directive has been instantiated. Normally constructors are used for the initialization of variables, but when we have task related to bindings we simply move to the angular ngOnInit lifecycle hook.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mahima Gautam
Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.