Difference Between Constructor vs NgOnInit in Angular
You must have heard the terms constructor and ngOnInit. In fact, it is one of the most frequently asked interview questions in Angular. Today we will see the answers to this question in detail.
Today's Agenda
Q01. What is the order precedence of the constructor and ngOnInit() execution in Angular?
Q02. What is a constructor in Angular?
Q03. What is ngOnInit() in Angular?
Q04. What is the Lifecycle hook in Angular?
Q05. What is the difference between constructor vs ngOnInit() in Angular?
Introduction
A constructor is nothing but a special type of method without any return type which has the same name as the class. We can also have multiple constructors in a class. Constructors are called automatically when we create the object of the class.
Constructors are used to initialize the data members or fields of the class while creating the object of the class. One of the common uses of a constructor is to initialize the read-only fields because read-only fields can only be initialized either at the time of declaration or in the constructor itself. Constructors are also mostly used in dependency injection. You can read more about constructors here.
Before going deep dive into the discussion, let's understand some basic terminology first:
Constructor in Angular (TypeScript)
We know that Angular uses TypeScript as the language to develop the application. TypeScript offers full support for the class keyword introduced in ES2015. Class constructors are very similar to functions. You can add parameters with type annotations, default values, and overloads. Like C# in typescript and Javascript also you can have read-only fields. Fields prefixed with the read-only modifier prevent assignments to the field outside of the constructor i.e. read-only field can only be assigned (initialized) in the constructor. You can watch about const vs. readonly here.
class CalculateArea {
PI: number ;
constructor() {
this.PI = 3.14;
}
}
Like other languages with object-oriented features, classes in JavaScript can also inherit from base classes. You can use the implements clause for that. So just like JavaScript, you can have a base class as well. In this case, you need to call super(); in your constructor body before using any "this. members".
There are just a few differences between constructor signatures vs. function signatures:
1. Constructors cannot have type parameters i.e. these belong on the outer class declaration.
2. Constructors cannot have return type annotations i.e. the class instance type is always what’s returned.
Lifecycle Hooks in Angular
In Angular, every component has a lifecycle. Angular creates and renders these componentsas well as destroys them before removing them from the DOM. This is achieved with the help of lifecycle hooks. Lifecycle hooks are predefined methods in Angular that enable developers to access different stages of a component or a directive's lifecycle.
To use a lifecycle hook, you can override some methods in a component, such as ngOnInit() or ngAfterViewInit(). If available in a component, these methods will be called by Angular automatically. This is why these are called lifecycle hooks. You can read more about lifecycle hooks here.
NgOnInit() Lifecycle Hook
The ngOnInit() is the second lifecycle hook which is the most often used hook. It is called only once, after the ngOnChanges() hook to indicate that the component has been created. It is called after the constructor is called or after the component’s inputs have been initialized. It accepts no arguments and returns a void type.
It is used to initialize the component and set the input properties of the component. It is used to perform any additional initialization that is required for the component. It is an ideal place to perform any initialization logic that depends on the input properties. If you have to process a lot of data during component creation, it’s better to do it inside the ngOnInit() hook rather than the constructor.
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() {
console.log('Constructor is invoked');
}
ngOnInit() {
this.processData();
}
processData(){
console.log('Data is processed');
}
title = 'crackjob-app';
}
Constructor vs. NgOnInit()
In Angular, both constructor and ngOnInit are commonly used in components. While they may seem similar initially, they serve different purposes and have some key differences.
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.
On the other hand, ngOnInit is a lifecycle hook in Angular that is called after the constructor or after the component’s inputs have been initialized. It is used to perform any additional initialization that is required for the component. The ngOnInit is commonly used to call services or to set up subscriptions.
Constructor vs. NgOnInit in Angular | ||
---|---|---|
Sr. No. | Constructor | NgOnInit Hook |
1. | Constructors are executed always before ngOnInit() hook. | The ngOnInit() always executes after the constructor execution. |
2. | Constructors are mostly used for DI and initialization of instance variables. | On the other hand, ngOnInit is used for initialization tasks that require the component to be fully initialized. |
3. | A constructor cannot access the component’s DOM elements. | On the other hand ngOnInit() can access the component’s DOM elements. |
4. | A constructor is executed every time a component is created. | But ngOnInit is executed only once after the component has been initialized. |
5. | A constructor can be used in both classes and directives. | But ngOnInit is only available in classes that implement the OnInit interface. |
6. | A constructor can be used to configure the component’s metadata, such as its selector and inputs. | But the ngOnInit cannot be used to configure the component’s metadata. |
7. | A constructor cannot use @ViewChild or @ContentChild decorators to query child components or content projection. | However ngOnInit can use @ViewChild and @ContentChild decorators to query child components or content projection. |
8. | A constructor is the default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. | On the other hand, ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component. |
9. | There is no dependency for using constructor in any class. | But you have to import OnInit and implement the OnInit Interface in order to use ngOnInit(), however is not mandatory but considered good practice. |
Wrap Up
- Both Constructor and ngOnInit() are two different things in Angular. A constructor is always invoked before the ngOnInit().
- Constructor is mostly used for Dependency Injection and initialization of instance variables. On the other hand, ngOnInit is used for initialization tasks that require the component to be fully initialized.
- A constructor cannot access the component’s DOM elements but ngOnInit() can access the component’s DOM elements.
- A constructor cannot use @ViewChild or @ContentChild decorators to query child components or content projection. However, ngOnInit can use @ViewChild and @ContentChild decorators to query child components or content projection.
- A constructor is executed every time a component is created. However, ngOnInit is executed only once after the component has been initialized.
- A Constructor can be used in both classes and directives. But ngOnInit is only available in classes that implement the OnInit interface.
Recommended
- Interface vs. Abstract Class in .Net
- SQL Merge Statement - EVIL or DEVIL
- Difference Between React vs. Angular
- Difference Between Constructor vs. NgOnInit in Angular
- Constructor Execution Order in C#
- Difference Between padding vs. margin in CSS
- Constructor Execution Order in C#
- Difference Between padding vs. margin in CSS
- Difference Between document.ready() vs. window.onload() in jQuery
- Difference Between target="_blank" vs target="blank" in HTML
Tags:
angular-interview