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
- 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 AngularngOnInit
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 AngularDifference 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.
Similar Reads
Input Decorator In Angular
The @Input decorator in Angular is used to pass data from the parent to child components. It allows a parent component to bind data to properties in a child component enabling the sharing of data between components in a hierarchical relationship. The @Input decorator is important for communication b
4 min read
ng-content in Angular
The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content. Syntax:Â <ng-co
2 min read
Introduction to Angular Universal
In the last few years, Angular become one of the most famous front-end framework to develop single page application. Most of the people think Angular only works on client-side but its partially true as there is one concept in Angular which explain some part of the application to be rendered at serve
4 min read
Introduction to Angular Concepts
Angular, a powerful front-end framework developed by Google, has revolutionized the way modern web applications are built. For newcomers to web development, Angular can seem to be a great choice due to its features, concepts, and terminologies. In this article, we'll see more about the journey of An
5 min read
What is the Difference between Constructor and ngOnInit in AngularJS ?
Constructor: Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular are preferably the Dependency Injector (DI), analyzes the builder's components and when creating a new feature
3 min read
Angular ng-container
The ng-container is an Angular element that acts as a grouping mechanism. It does not render any additional HTML in the DOM which makes it great for scenarios where you need to apply structure directives like *ngIf, *ngFor, or *ngSwitch but do not want to create additional elements like div or span
4 min read
Purpose of NgModule Decorator in Angular
The NgModule decorator in Angular is like a blueprint for organizing and configuring different parts of your application. It's like a set of instructions that tells Angular how to assemble the various components, directives, pipes, and services into cohesive units called modules. These modules help
5 min read
Component Communication in Angular
Angular, as a robust front-end framework, allows you to build complex and interactive web applications by creating reusable components. One of the key aspects of building such applications is effective communication between these components. There are a lot of instances where we need to transfer dat
12 min read
Angular 7 | Introduction
Angular 7 is a TypeScript based front-end web framework by Google. It enables you to create Single Page Applications(SPA) with the help of the concept of components. The components in Angular 7 are structured like a tree i.e. there are parent and child components in which each child component is con
2 min read
Angular 4 | Introduction
Angular 4 was released 5 years after the official release of AngularJS. Between these two versions, Angular 2 was introduced which was a complete re-write of AngularJS. The 'MVC' architecture of AngularJS was discarded a new 'service-controller' architecture was introduced in Angular 2. After Angula
2 min read