Interview Question - What is the difference between Angular Component Constructor and OnInit?

Get support on Angular & Typescript related technology.
Post Reply
Site Admin
Posts: 44

Interview Question - What is the difference between Angular Component Constructor and OnInit?

Post by admin » Mon Oct 14, 2019 5:22 pm

Angular Component Constructor Vs OnInit

Constructor : constructor is a default method runs (by deafult) when component is being constructed. When you create an instance of a class that time also constructor(default method) would be called. So in other words, when component is being constructed or/and an instance is created constructor(default method) is called and relevant code written within is called. Basically and generally in Angular2 it used to inject things like services when component is being constructed for the further use.

OnInit: ngOnInit is component's life cycle hook which runs first after constructor(default method) when component is being initialized.

So, Your constructor will be called first and OnInit will be called later after constructor method.

Constructor is predefined default method of the typescript class. There is no relation between Angular and constructor. Normally we use constructor to define/initialize some variables, but when we have tasks related to Angular's bindings we move to Angular's ngOnInit life cycle hook. ngOnInit is called just after the constructor call. We can also do the same work in the constructor but its preferable to use ngOnInit to start Angular's binding.

in order to use ngOnInit we have to import this hook from the core library:

Code: Select all

import {Component, OnInit} from '@angular/core'
Then we implement this interface with exported class (this is not compulsory to implement this interface but generally we did).

Example of using both:

Code: Select all

export class App implements OnInit{
     //called first time before the ngOnInit()

     //called after the constructor and called  after the first ngOnChanges() 
Look at the below chart I created which shows the lifecycle of Angular-

Post Reply