Confused between Constructor and ngOnInit in Angular? Don’t know where to use these methods? We got everything covered in this tutorial.

ngOnInit is a method provided by Angular while the constructor is not an insider of the framework. If you’re already familiar with object-oriented programming, you must have known that Constructor is a special method used in instances when a class is created. Even though the constructor name is the same as the class name in languages such as Java and a few other languages.

In ECMAScript 6, (ECMAScript is a standard for JavaScript) the classes were introduced in which the constructor method is used to initialize the properties of the class. You should note that in Javascript, the constructor method name is constructor only, it is not given a class name.

class Sport {

constructor(name, type) {

this.name = name;

this.type = type;

}

}

sportObj = new Sport(‘cricket’, ‘outdoor’);

When creating an instance the constructor is invoked. Whether it is implemented or not in the class since the typescript class is compiled to a function.

// Compiled version of above code

function Sport(name, type) {

this.name = name;

this.type = type;

}

In the case of the absence of a constructor, an empty function is created in transpired JavaScript.

class Sport {

}

function Sport() {

}

Let’s move to the important part. The usage of constructors in Angular is dependency injection. The dependencies of the component can be injected in the constructor which makes it available in the component class.

import { Router } from ‘@angular/router’;

export class ProductComponent {

constructor(private router: Router) {

}

}

Then the router can be accessed as this.router

A constructor is a good place to inject dependencies that are available outside the component. Setting up the dependencies in the constructor makes those available for initialization work in the class. Constructor can be generally used to initialize properties as well.

#angular #programming #javascript #ecmascript #ngoninit

What Is The Difference between ngOnInit And Constructor
1.20 GEEK