Difference between constructor and ngOnInit in Angular 8


We can create robust applications using a number of life cycle functions using Angular. As it is the response of the event, the constructor and ngOnInit play important roles in developing applications. May this constructor and ngOnInit terms often confuse us.

Constructor and ngOnInit will be available from the life cycle hooks of a component. This will provide extensive benefits to us in developing applications.

Let’s check the differences below. Before that, let’s discuss the constructor and ngOnInit in detail.

What is the Constructor in Angular 8?

Constructor is a default method for a class and is called whenever we create new objects. It is generally used to initialize class members and ensures the proper execution of the roles in the class and its subsection.

Angular dependency injection analyzes the constructor parameters. When creating a feature by calling new class() tries to find the suppliers that match the builder’s parameter. Then resolve them and pass them to the similar components.

We can use constructor as a default constructor, which means without any parameters. We can use the constructor with private classes as parameters. We can inject our classes and we can define those classes as parameters of constructor. So, it will create instances of that classes.

Let’s see the example below.

Create a project first, using the command. Like,

ng create new ProjectName

Default Constructor

Default constructor nothing but without parameters.

Example

Write the following code in app.component.ts and run the project.

import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { messageFromConstructor: string = ""; constructor() { this.messageFromConstructor = "Constructor called"; } }

In app.component.html file, write code like given below.

<p>Constructor</p>
<p>{{messageFromConstructor}}</p>

Output

Constructor
Constructor called

Example

Let’s consider we have some service or component or any module to use in our component. Inject that file and assign parameters in constructor to use that one.

Create a service file "./app/sampleService.ts". Write code like

import { Injectable } from "@angular/core"; @Injectable() export class SampleService { constructor() {} showMessage() { return "Message from angular service"; } }

Import service in main module i.e. app.module.ts file like −

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

Now, Inject created service in our component i.e. app.component.ts file. Like,

import { Component } from "@angular/core"; import { SampleService } from "./sampleService"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { messageFromConstructor: string; constructor(private readonly sampleService: SampleService) { this.messageFromConstructor = this.sampleService.showMessage(); } }

Here, we imported service class and injected service as parameter of constructor.

Now, write the code to display the data i.e. app.component.html

<p>Constructor</p>
<p>{{messageFromConstructor}}</p>

Output

Constructor
Message from angular service

What is ngOnInit() Function?

The ngOnInit() is a life cycle hook managed by angular and it is called to show that angular is created a component. Actual business logic performed in this method. We need to import OnInIt to use this method.

Create a project with command. Like,

ng create new projectName

Example

Now, in app.component.ts file, write the code like given below.

import { Component, OnInit } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { messageFromConstructor: string = ""; messageFromOnInIt: string = ""; constructor() { this.messageFromConstructor = "Constructor called"; } ngOnInit() { this.messageFromOnInIt = "ngOnInit called!!"; } }

Now, In app.component.html file. Write code like given below.

<p>Constructor</p> <p>{{messageFromConstructor}}</p> <p>NgOnInIt</p> <p>{{messageFromOnInIt}}</p>

Output

Constructor
Constructor called
NgOnInIt
ngOnInIt called!!

The ngOnInit() will be executed, when angular done with the creating the component. This method is called after constructor and after first ngOnChanges also.

Differences between Constructor and ngOnInit()

The following table highlights the major differences between the Constructor and ngOnInit −

Constructor

ngOnInit

It is typescript feature, nothing to do with it.

It is one of the life-cycle hooks of an angular component.

Constructor is transformed into a function with the same name as class created.

It is being added to the prototype of the class is created.

Called by the JS engine.

Called by an angular.

Used to inject dependencies.

Used to write business logic.

It is called when object of the class is created.

It is called when angular completes the creation of component.

Conclusion

Constructor is used to initialize the class. It doesn’t have any connection with HTML DOM elements. ngOnInit() used to write business logic. Using ngOnInit(), we can perform actions with the HTML DOM elements. Because it is called after the entire component being created.

Updated on: 21-Feb-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements