The Constructor, a default method of the class, is called when the class is instantiated and makes sure that the fields of the class and its subclasses are properly initialized. Dependency Injector (DI), or Angular, analyses the function constructor parameters before trying to locate providers that match the types of the function constructor parameters, resolving them, and passing them to the function constructor when it calls new MyClass() to build a new instance.
When Angular is finished building the component, it calls the life cycle hook ngOnInit.
Most of the time, we avoid doing anything in the function constructor by using ngOnInit for all initialization and declaration. The only “work” that the function constructor should perform is initializing class members. Therefore, you should only use function constructor to set up Dependency Injection. Better to “start” from ngOnInit(), which is where/when component bindings are determined.
Example
// import OnInit
import {Component, OnInit} from '@angular/core';
...
@Component({
...
})
// implementing OnInit
export class AppComponent implements OnInit {
constructor() {
// constructor called first time before the ngOnInit()
}
ngOnInit() {
// called after the constructor and called after the first ngOnChanges()
}
}
Difference between ngOnInit()
and constructor()
- All initialization and declaration operations are performed using function constructor().
- Writing actual work in the function constructor() should be avoided.
- The function constructor() should not perform any actual “work,” merely initialize class members.
- Therefore, to set up Dependency Injection, initialize class fields, etc., we should utilize the function constructor() method.
- The “real work code” that must be run as soon as the class is instantiated should be put in ngOnInit().
- similar to loading database data to display to the user in your HTML template view. Such programming should be done in ngOnInit ().
Conclusion
- Initialize class members in the Constructor.
- The functionality that has to run right away when the class is created should go in the ngOnInit() function.