The difference between Constructor and ngOnInit in Angular 9
This tutorial explains you the difference between Constructor and ngOnInit in Angular 9. A constructor in typescript is a special function of the class which is responsible for initializing the variables of the class. The ngOnInit method is one of an Angular component’s life cycle methods and this method is called shortly after the component is created.
Constructor in Angular – TypeScript
Most of us would have have studied or know about how constructors are used in languages like Java and C#. But constructors concept are new to people who worked only in JavaScript technologies. The constructor is the default method of the class which will be executed when the class is instantiated.
Constructors in TypeScript is function or method which will be called to create an object of the class. You have to define constructor in the class file as shown below. Note, in TypeScript only one constructor is allowed unlike any other object-oriented programming languages.
Constructor ensures the proper initialization of class members or variables declared in the class as shown below.
server.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector:'app-server', templateUrl:'./server.component.html' }) export class ServerComponent implements OnInit { isRefreshAllowed: boolean; serverRefreshStatus: string; serverId: number; serverStatus: string = 'online'; constructor() { console.log('Inside ServerComponent class constructor'); this.isRefreshAllowed = false; this.serverRefreshStatus = 'Server was not refreshed!'; this.serverId = 10; } ngOnInit(): void { console.log('Component has been initialized'); } getServerStatus(){ return this.serverStatus; } onServerRefresh(){ this.serverRefreshStatus = 'Server Refreshed!'; } }
Output
Parameterized Constructor in Angular
TypeScript also supports the following other types of constructors; parameterized constructor and parameterized constructor with optional arguments. But only one constructor is allowed.
When you create new instance of the class you must pass exact match and same type of the arguments or parameters type to the constructor of the class.
The following is an example for parameterized constructor with optional arguments.
constructor(arg1: <type of argument>, arg2 : <type of argument>, arg3? : <type of argument>) { }
Like in any other object-oriented language, TypeScript provides option for having optional argument in the constructor. The ? keyword is used in the argument to make the parameter optional for the constructor. All the optional parameters of a constructor should be written after all the mandatory parameters in the constructor.
Constructor in Angular for Injecting Services
You can tell Angular to inject a dependency in a component’s constructor by specifying a parameter in the constructor as shown. Here ServerComponent constructor look for ServerRefreshService to be injected.
Let’s modify our code above to fetch and set the serverRefreshStatus value using ServerRefreshService which is added as a dependency in the ServerComponent class. To tell Angular to inject this dependency we have specified this as a parameter in the constructor.
import { Component, OnInit } from '@angular/core'; @Component({ selector:'app-server', templateUrl:'./server.component.html' }) export class ServerComponent implements OnInit { isRefreshAllowed: boolean; serverRefreshStatus: string; serverId: number; serverStatus: string = 'online'; constructor(serverRefreshService : ServerRefreshService) { console.log('Inside ServerComponent class constructor'); this.isRefreshAllowed = false; this.serverRefreshStatus = serverRefreshService.getServerRefreshStatus(); this.serverId = 10; } ngOnInit(): void { console.log('Component has been initialized'); } getServerStatus(){ return this.serverStatus; } onServerRefresh(){ this.serverRefreshStatus = 'Server Refreshed!'; } }
ngOnInit in Angular
ngOnInit is a life cycle hook or callback method which will be invoked immediately by Angular to indicate that Angular is done creating the component. This purpose of this method is to handle any other additional initialization tasks right after Angular has initialized all data-bound properties.
You need to import OnInit and your component class should implement that. And define ngOnInit method to handle initialization tasks.
For example, the following server.component.ts class shows how a component class can implement OnInit interface to define its own initialization method (ngOnInit).
import { Component, OnInit } from '@angular/core'; @Component({ selector:'app-server', templateUrl:'./server.component.html' }) export class ServerComponent implements OnInit { constructor() { console.log('Inside ServerComponent class constructor'); } ngOnInit() { console.log('Inside ngOnInit method'); } }
Output
Inside ServerComponent class constructor Inside ngOnInit method
Although, implementing OnInit in every component is not mandatory. But considered good practice.
Difference between constructor and ngOnInit in Angular
- We use constructor() for all the initialization of class members or variables.
- The constructor() should only be used to initialize class members and shouldn’t do other “work”.
- You can use constructor() to setup Dependency Injection so that you can Initialize class members.
- ngOnInit() is a better place to write other initialization tasks that we need to execute once the class is instantiated.
- For example, if you want to load data from Database in your HTML template view. Then such code should be written in ngOnInit() method.
Conclusion
- Constructor() should be used only for initialization of class members.
- ngOnInit() method should be used for other initialization tasks which need to be executed right after class is instantiated.
Also See:
- String Interpolation in Angular 9
- Create a new component in Angular 9 with CLI and without CLI
- How to include Bootstrap to your Angular 9 Project ?
- Angular TypeScript Vs ES6 Vs ES5
- How to change angular port from 4200 to some other port ?
- Port 4200 is already in use while running ng serve Angular CLI command
- Data binding in Angular 9
- Get index of ngFor element using index as value in attribute