Difference between Constructor and ngOnInit?

 

In the context of Angular, constructor and ngOnInit serve different purposes and are used at different stages of a component's lifecycle.

constructor:

  1. The constructor is a TypeScript class method and is not specific to Angular. It's a standard part of a class definition in TypeScript.

  2. It is called when an instance of the component class is created. It's typically used for initializing class properties and dependencies. However, it should not be used for making HTTP requests or accessing the DOM, as Angular-specific initialization should be done in ngOnInit.

ngOnInit:

  1. ngOnInit is an Angular lifecycle hook specifically provided by the Angular framework.

  2. It is called after the component's data-bound properties have been initialized and before the view is initialized. This is the appropriate place to put initialization code that depends on the component's inputs.

  3. ngOnInit is often used for fetching data from an API, initializing component properties, or performing other setup tasks specific to Angular.

Here's an example that illustrates the difference between constructor and ngOnInit:

typescript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: ` <h1>{{ message }}</h1> ` }) export class ExampleComponent implements OnInit { message: string; constructor() { // Constructor is called when the component is instantiated. // It's a good place for dependency injection and property initialization. this.message = 'Hello from Constructor!'; } ngOnInit() { // ngOnInit is an Angular lifecycle hook. // It's called after the constructor and after Angular has initialized // data-bound properties. this.message = 'Hello from ngOnInit!'; } }

In this example:

  • In the constructor, we initialize the message property. However, this initialization could be overridden later in the ngOnInit.

  • In the ngOnInit, we set the message property to a different value. This is a common pattern in Angular components to perform component-specific initialization that relies on data bindings and Angular's lifecycle.

Remember that Angular-specific tasks should generally be performed in ngOnInit, while the constructor is primarily used for TypeScript class-level initialization.

Comments