Difference between Constructor and ngOnInit

Difference between Constructor and ngOnInit

The angular bootstrap process has below defined steps.


  • Constructing components tree - Constructor is called when Angular constructs tree of the components in our project. A component tree view is generated in this step with constructor been called for each class instance. A DOM element is set up for components. 
  • Running change detection - All the lifecycle hooks are called in this step. Before this step only, the constructors are already called for all the components. The component tree is already in place. Template nodes are set up in the DOM. Changes related to @Input and @Output bindings and change detection cycle starts here. Bindings will get updated and data will be shown during this step.

Constructor

The constructor is a typescript method that is associated with a typescript class by default. It is called when we create a new instance of the class. The constructor is used for defining variables, setting values for them, etc. 
  • It has no relation to Angular and its bindings.
  • The constructor is a typescript concept which we used for dependency injection(DI). DI will look at the parameters of the constructor when it creates a new instance of the class. We generally inject services in the constructor.
  • 
    import { Component } from '@angular/core';
    import { UtilityService } from './services/utility-service/utility.service';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      title = 'app';
    
      constructor(private _utilService: UtilityService){}  // DI in constructor
    }
    
    
  • It is called when we write a new className(). All the variables will be initialized in the constructor.
  • It is used to set up dependency injection(DI) because DI looks into constructor parameters to find providers and services, analyze the type of parameters in the constructors and finally injecting them in the constructor.
  • The constructor is called before the ngOnInit() lifecycle hook.
  • The constructor is associated with the first step which is constructing components tree during bootstrapping of our Angular application.
  • @Input, @ViewChild, @ContentChild, ElementRef are undefined in the constructor.
  • It is advisable to do only DI using a constructor. Angular binding tasks shouldn't be defined here.

NgOnInit

NgOnInit is a lifecycle hook for a component lifecycle. We need to import this hook from @angular/core to implement in our component class. 

import { Component, OnInit } from '@angular/core';

  • It is called after the constructor.
  • We will write all the logic hereafter the component is initialized properly.
  • It is called after the ngOnChanges() lifecycle hook. As soon as there is any change in input and output bindings,ngOnChanges() is called.
  • After the component is initialized fully, ngOnInIt() will be called.
  • ElementRef and nativeElement can be used inside this as this.elementRef.nativeElement
  • It is part of the change detection cycle of Angular.

Example 

export class App implements OnInit{ 
 fcCustomers: FormControl;
  constructor(private elementRef: ElementRef,
              private _userSrv: UserService,   ) {
     // this.elementRef.nativeElement is undefined here
  }

  ngOnInit() {
     // this.elementRef.nativeElement can be used from here on
       this.loadUserProfile();  //Logic is written here
       this.fcCustomers.setValue('');  // Binding related initialisation is written here
  }
   loadUserProfile(){
      this.profile = this._userSrv.getUserProfile().then((res: any) => res.data); // Fetching data from User Service
   } 
}

Comments