What is difference between constructor and ngOnInit in Angular?

By learning the difference between constructor() and ngOnInit(), one can master correct dependency injection, handling asynchronous operations appropriately, optimizing performance, and preventing bugs.

For detailed knowledge about dependency injection, check out the What is Angular Dependency Injection? Answer.

The constructor() method

  • Constructors are derived from object-oriented programming and aren’t solely the concept of Angular. The primary function of a constructor is to create an instance of a component class.

  • Constructor is a default method for a class that initializes classes and subclasses and ensures proper execution of roles.

  • Remember that whenever we call a class, we have to pass the exact match of the parameter type to the constructor of that class, e.g., Student(arg1:string, arg2:string, arg3:int). These arguments must be of the same type in the constructor of the Student() class.

  • It runs before Angular fully initializes the components view and data bindings.

  • It might not have access to specific properties like @Input values or the DOM.

Working: Constructor parameters are analyzed by Angular dependency injection. Whenever a class instance is created, the system searches for matching providers that define how to construct those dependencies. Subsequently, the resolved dependencies are then passed to similar components.

Example

Let’s see how the constructor works:

import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
template: `
<h1>{{ message1 }}</h1>
`,
})
export class SampleComponent implements OnInit {
message1: string;
constructor() {
this.message1 = 'This is a constructor';
}
}

Explanation:

Line 1214: We set the initial value of the message1 property when an instance of the SampleComponent class is created.

The ngOnInit() method

  • It’s an Angular-specific lifecycle hook. It allows us to run code at different stages of an element’s life.

  • We need to import OnInit to use this method.

  • The actual business logic is performed in this method. When called, it indicates that Angular is done creating the component.

  • This method is called after Angular has initiated the component properties, inputs, and data bindings.

  • It also guarantees that the component’s environment is ready before running the initialization logic.

Example:

Let’s see the difference with the code:

Explanation:

In app.component.ts file:

Line 13–16: We create constructor() for basic initialization.

Line 19–25: We create ngOnInit() for more complex logic.

Line 20–21: We use ngOnInit to change helloWorld, showing how it can improve or adjust the starting value set in the constructor.

Line 23–24: We increased the value of the counter property in ngOnInit, demonstrating that it can perform actions that rely on the component being set up.

Difference between constructor() and ngOnInit()

Aspect

constructor()

ngOnInit()

Initialization timing

Right after the instance of a class is created

After component is set up by Angular

Recommended usage

Setting up, dependency injection

Performing operations, loading data

Purpose

It’s used for initilization class members.

It’s used for the execution of actual work. It’s the place to put code that needs to execute as soon as the class is instantiated.

Template interaction

Not ideal for template

Ideal for template

Access to dependencies

Constructor might not have full access to dependencies

Has full access to dependencies

DOM

Limited

Ideal for DOM

Conclusion:

The constructor() is a place for basic setup and dependency injection, whereas ngOnInit() is a dedicated lifecycle hook for advanced initialization tasks.

Copyright ©2024 Educative, Inc. All rights reserved