Open In App

Constructor vs ngOnInit in Angular

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Angular, both constructor and ngOnInit are lifecycle hooks that are commonly used in components. While they may seem similar at first, they serve different purposes and have some key differences. In this article, we will explore the difference between constructor and ngOnInit in Angular.

Constructor: A Constructor is a special method that is automatically called when an instance of a class is created. It initializes the properties of the class and does any other necessary setup. In Angular, constructors are used to inject dependencies, such as services or other components, into a component.

Syntax:

import { Component } from '@angular/core';

@Component({
      selector: "app-example",
      template: "<h1>{{title}}</h1>"
})
export class ExampleComponent {
      title: string;

      constructor() {
        this.title = "...";
      }
}

Example 1: In this example, the constructor has been created & will be executed when the class is instantiated, along with ensuring proper field initialization in the class and its subclasses.  

  • app.component.ts

Javascript




import { Component } from "@angular/core";
  
@Component({
    selector: "my-app",
    template: 
        "<div><h1>{{data}}</h1><h1>{{subtitle}}</h1></div>",
    styles: [`div { 
        color: green;
    }`],
})
export class AppComponent {
    title: string;
    subtitle: string;
    data: string;
  
    constructor() {
        this.title = "Welcome to GeeksForGeeks";
        this.data = "Welcome to GeeksForGeeks";
        this.subtitle = "from constructor";
    }
}


  • app.module.ts

Javascript




import { BrowserModule } 
    from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
  
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

 

ngOnInit: ngOnInit is a lifecycle hook in Angular that is called after the constructor is called and after the component’s inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions.

Syntax:

import { Component } from '@angular/core';

@Component({
  selector: "app-example",
  template: "<h1>{{title}}</h1>"
})
export class ExampleComponent {
  title: string;
  data: string;

  constructor() {
    this.title = "...";
  }
  
  ngOnInit(){
    this.data = "..."
  }
}

Example 2: In this example, we have imported OnInit (life cycle hook) that is invoked by the Angular to represent the Angular is done in creating the component.

  • app.component.ts

Javascript




import { Component, OnInit } from "@angular/core";
  
@Component({
    selector: "my-app",
    template: 
        "<div><h1>{{data}}</h1><h1>{{subtitle}}</h1></div>",
    styles: [`div { 
        color: green;
    }`],
})
export class AppComponent {
    title: string;
    subtitle: string;
    data: string;
  
    constructor() {
        this.title = "Welcome to GeeksForGeeks";
    }
  
    ngOnInit() {
        this.data = "Welcome to GeeksForGeeks";
        this.subtitle = "from ngOnInit";
    }
}


  • app.module.ts

Javascript




import { BrowserModule } 
    from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
  
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

 

Difference between constructor and ngOnInit in Angular:

Constructor 

ngOnInit

Executes before ngOnInit.

Executes after the constructor.

Used for dependency injection and initializing instance variables.

Used for initialization tasks that require the component to be fully initialized.

Cannot access the component’s DOM elements.

Can access the component’s DOM elements.

Executed every time a component is created.
 

Executed only once after the component has been initialized.

Can be used in both classes and directives.

Only available in classes that implement the OnInit interface.

Can be used to configure the component’s metadata, such as its selector and inputs.

Cannot be used to configure the component’s metadata.

Cannot use @ViewChild or @ContentChild decorators to query child components or content projection.

Can use @ViewChild and @ContentChild decorators to query child components or content projection.

Overall, Constructor and ngOnInit are both important lifecycle hooks in Angular, but they have different use cases and limitations. Understanding these differences is crucial for writing efficient and effective Angular components.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads