Open In App

Constructor vs ngOnInit in Angular

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Two important concepts in Angular that often cause confusion among developers are the constructor and ngOnInit. Both play important roles in the lifecycle of Angular components but serve different purposes.

Understanding Constructor vs ngOnInit in Angular can help in writing more efficient and maintainable code. In this article, we’ll explore what the constructor and ngOnInit are, their syntax, features, and uses and what is the difference between Constructor and ngOnInit.

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 = "...";
    }
}

Features of Constructor

  • Automatically called when the class is instantiated.
  • Used to initialize class properties.
  • Executes immediately upon component creation.
  • Handles dependency injection.

Uses of Constructor

  • Initializing class properties.
  • Injecting dependencies, such as services.
  • Setting up initial state or configurations required before the component starts interacting with data or services.

Example: 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.  

JavaScript
//app.component.ts

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";
    }
}
JavaScript
//app.module.ts

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:

Constructor In Angular

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 = "..."
    }
}

Features of ngOnInit

  • Called once after the component's data-bound properties have been initialized.
  • Used for component initialization that requires the component to be fully set up.
  • Allows interaction with input properties that Angular sets up before calling ngOnInit.

Uses of ngOnInit

  • Fetching data from APIs after the component is ready.
  • Setting up additional configurations that depend on data-bound properties.
  • Initializing third-party libraries that need the component to be fully rendered.

Example: 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.

JavaScript
//app.component.ts

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";
    }
}
JavaScript
//app.module.ts

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 in Angular

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.

Cannot use @ViewChild or @ContentChild queries; use ngAfterViewInit for @ViewChild and ngAfterContentInit for @ContentChild.

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.


Next Article

Similar Reads