Difference between NgOnInit and Constructor in Angular

    Jul 25, 2020       by Pankaj Kumar
difference-between-ngOnInit-and-constructor.jpg

While working with angular, the use of Constructor and NgOnInit seems very similar. So most of the developers get confused about the difference between Constructor and NgOnInit. Also, this question is frequently asked in the interviews, So in this article, we will see the differences between Constructor and NgOnInit.

 

What is Constructor?

 

In class-based object-oriented programming, A constructor is a special method that is called whenever we create new objects. And generally used for initializing the class members.

 

Any developer who has worked on any programming language should have heard about this term.

class Abc{

     a;

     b;

     constructor(a, b) {

        this.a = a;

        this.b = b;

     }

     multiply(){

      return this.a*this.b;

     }

}

 

var newObj = new Abc(5,10); // created new object

console.log(newObj.multiply()); // Output: 50

 

In the above code, whenever a new object is created of the class the values passed in the argument will be assigned to class variable a and b using constructor. This way it assigns the values automatically while creating the object.

 

What is ngOnInit() in Angular?

 

ngOnInit is a life cycle hook managed by Angular. It is executed when Angular done with the creating of component DOM. It initializes the directive or component after Angular first displays the data-bound properties and sets the directive or component's input properties. It is called once, after the constructor execution and first ngOnChanges().

In order to use OnInit we have to import it in the component class and implement like this: 
 

// import OnInit

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

@Component({

....

})

// implement OnInit

export class AppComponent implements OnInit {

  constructor(){

  // It is called before ngOnInit()

  }

 

  ngOnInit(){

    // It is called after constructor and after first hook ngOnChange()

  }

}

 

 

Difference between constructor() and ngOnInit() 

  • In Angular, We mainly use constructor dependency Injection/initialization/declaration.
  • Initial data loading on the page should be called inside ngOnInit.
  • Constructor initially performs all the tasks required which makes ngOnInit a good place to perform initialization logic

 

Conclusion

In this article, We learn about the Difference between NgOnInit and Constructor in Angular

I hope this article helped you to get in-depth knowledge about the topic. You can also find other demos/articles at Angular Sample Projects here to start working on enterprise-level applications.

Let me know your thoughts over email at pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: