What is the difference between constructor and ngOnInit in Angular?

Angular ngOnInit

The Constructor is a default method of the class that is executed when the class is instantiated. It ensures proper initialization of all class members (fields/properties) and subclasses. It is JavaScript/TypeScript special method, not Angular related. Developer. Mozilla defines JavaScript as “a special method for creating and initializing an object created within a class.” It also enables you to provide custom initialization before calling any method on an instantiated object.
It is important to understand the execution of the constructor does not mean Angular completed creating the component.

Let’s elaborate this further with a few examples:

ngOnInit is a life cycle hook called by Angular to indicate that it completes creating the component or signaling initialization of bindings. The Angular official documentation defines it as:
“A callback method that is invoked immediately after the default change detector has checked the directive’s data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.”

The flow of execution:
Constructor() –> ngOnChanges() –> ngOnInit()

Angular calls the component constructor when components tree constructs. All life-cycle hooks are called as part of running change detection.
Also, the DOM native elements are available in ngOnInit not in the constructor which means they are undefined/inaccessible for manipulated.

When to use Constructor or ngOnInit?

  • Use the constructor or ngOnInit for initialization logic depending on the availability of what you need
  • Use the constructor to setup Dependency Injection
  • Use the constructor if you want it happens before the execution of ngOnInit
  • Use the constructor to initialize class members
  • Use ngOnInit for all the initialization/declaration
  • Use ngOnInit if you are manipulating DOM native elements

The constructor is part of ES6 JavaScript class and ngOnInit relates to the Angular life-cycle. The constructor executes before ngOnInit and they serve different purposes explained above in detail.

Citations:
https://angular.io/api/core/OnInit
https://stackoverflow.com/a/45430181/894532
https://stackoverflow.com/a/35763811/894532