A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/angular-js/constructor-vs-ngoninit-in-angular/ below:

Constructor vs ngOnInit in Angular

Constructor vs ngOnInit in Angular

Last Updated : 17 Sep, 2024

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 Uses of Constructor

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 Uses of ngOnInit

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4