What is difference between constructor and ngOnInit in Angular?

In Angular, the constructor() is a special method used to initialize a class instance and inject dependencies, while ngOnInit() is an Angular-specific life cycle hook that runs after the component is fully initialized, allowing for the execution of logic once bindings and properties (such as @Input) are available. By learning the difference between constructor() and ngOnInit(), one can master correct dependency injection, handle asynchronous operations appropriately, optimize performance, and prevent bugs.

Key takeaways:

  • Use constructor() for basic class setup and dependency injection, and ngOnInit() for advanced initialization tasks such as fetching data or interacting with the DOM.

  • constructor() is called first when a class instance is created, while ngOnInit() is called after Angular sets up the component’s environment.

  • ngOnInit() ensures that the component’s properties are fully accessible and ready for logic execution, unlike the constructor, which may not have access to certain Angular-specific properties.

The constructor() method

The constructor() method is derived from object-oriented programming and isn’t solely the concept of Angular. The primary function of a constructor is to create an instance of a component class. It 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 of the constructor() method

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.

Code 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';
}
}

Code explanation

In the above code:

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

The ngOnInit() method

The ngOnInit() method is an Angular-specific life cycle 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.

Code example

Let’s see the difference with the code:

Code explanation

In the app.component.ts file:

  • Lines 13–17: We create the constructor() method for basic initialization.

  • Lines 20–26: We create the ngOnInit() method for more complex logic. We use the ngOnInit() method to change helloWorld, showing how it can improve or adjust the starting value set in the constructor. 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

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 essential for class setup and dependency injection, but it’s not part of Angular’s life cycle hooks and should be used primarily for initial setup. The ngOnInit(), on the other hand, is the ideal place for executing code after Angular has initialized the component, making it suitable for tasks like fetching data, interacting with the DOM, and performing complex logic that requires a fully set-up component.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the purpose of ngOnInit() in Angular?

The ngOnInit() is used to run initialization logic after Angular has set up the component. It is ideal for executing operations that require access to component properties, @Input values, and the DOM. It’s typically used for fetching data from APIs, setting up event listeners, or performing any logic that depends on the component being fully loaded.


What is the difference between constructor and ngOnInit in Angular 17?

In Angular 17, the difference remains the same: constructor() initializes the class and injects dependencies, while ngOnInit() is a life cycle hook that runs after the component is fully set up. The ngOnInit() is better suited for data fetching, DOM interaction, and other tasks that require the component’s environment to be ready. The constructor() is part of TypeScript’s OOP model, while ngOnInit() is specific to Angular’s component life cycle.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved