The open blogging platform. Say no to algorithms and paywalls.

Difference between Constructor and ngOnInit in Angular.

image

Constructor

  • The Constructor is a default method of the class that is executed when the class is instantiated.

  • Constructor ensures proper initialization of fields (class members) in the class and its subclasses.

  • Angular Dependency Injector (DI) analyse the constructor parameters.

  • When we call new MyClass() it creates a new instance of the class.

  • While calling new MyClass() we must have to pass the exact match of the parameters type to the constructor of the class, example: new MyClass(arg1:number, arg2:string, argN:any)

  • These arg1:number, arg2:string, argN:any, must be of same type defined in constructor of class MyClass.

ngOnInit

  • ngOnInit is a life cycle hook called by Angular to indicate that the Angular is done creating the component.

  • In order to use OnInit we have to import it in the component class like this: import {Component, OnInit} from '@angular/core';

  • Actually implementing OnInit in every component is not mandatory. But considered good practice.

  • A class implements OnInit like this: export class AppComponent implements OnInit { }

Using ngOnInit

// 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()
  }

}

Angular calls its ngOnChanges() method whenever it detects changes to the value of input properties of the component (or directive).

Learn more about ngOnChanges() in Angular Project with Lifecycle Hooks.

Difference between ngOnInit() and constructor()

  • We use constructor() for all the initialization/declaration.

  • It’s better to avoid writing actual work in the constructor.

  • The constructor() should only be used to initialize class members but shouldn't do actual "work".

  • So we should use constructor() to setup Dependency Injection, Initialization of class fields etc.

  • ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.

  • Like** loading data **from Database — to show the user in your HTML template view. Such code should be written in ngOnInit().

Conclusion

  • Constructor initialize class members.

  • **ngOnInit() **is a place to put the code that we need to execute at very first as soon as the class is instantiated.

Next, I written a whole new Article

For you to understand the difference between initialization from ‘constructor’ and ‘ngOnInit’ in depth! That covers in ‘Lifecycle Hooks’.

Please follow the Link to understand Lifecycle Hooks: Angular Project with Lifecycle Hooks.

Done! 🤩 the difference was so simple.




Continue Learning