At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

What Is The Difference Between ngOnInit And Constructor?

  • By Gokulaselvan
  • March 18, 2020
  • 1111 Views

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.

Also Read

How To Consume Web API Using Angular

Can Initialization logic be placed in the constructor?

It is not recommended to place the initialization logic in the constructor. Here is why? Let’s think about initialization work- that may involve manipulating DOM elements, some logical functionality with input bindings.
During the invocation of the constructor, DOM is not rendered as well as the input properties are not bound which may result in null or undefined. Have a look at the example to have a better understanding. We have got one parent and one child component in which some data is passed from parent to child.

@Component({
 selector: 'parent-component',
 template: `
    <child-component [data]="text"></child-component>
 `
})
export class ParentComponent {
 text = 'Data from parent';
 constructor() { }
}
@Component({
 selector: 'child-component',
 template: `
    <p id="demo">Child Component</p>
 `
})
export class ChildComponent {
 @Input() data;
constructor() {
  let element = document.getElementById('demo');
  console.log('Child constructor - DOM access:', element);
  console.log('Child constructor - Input property access:', this.data);
  }
}

The output looks as below:
ngOnInit and ConstructorYou might notice the null and undefined in the output which clearly shows that DOM is not rendered as well as the input properties are not bound.

Lifecycle hook ngOnInit

On seeing the above problem of placing the initialization logic, it is required to know when the Angular component completes the initial setup.
Angular manages a lifecycle for each component, which goes through many stages from creation to destruction. To perform certain logics in different stages of a component, Angular provides lifecycle hook methods such as ngOnChanges, and ngOnInit.
To work with lifecycle hook methods the corresponding interface has to be implemented.
onChanges method is triggered whenever there’s a change in input properties. We will get a closer look at the OnInit method in this tutorial.
ngOnInit method is triggered once the initial setup of the component gets completed. That when the dependency injections are resolved and input properties are bound. ngOnInit is called only once during the lifecycle of an Angular component. After constructor, ngOnChanges will be called that binds the input properties and invokes the ngOnInit.

How to place initialization logic in OnInit?

This is the perfect place to put the initialization logic that the component needs. During this key moment in the lifecycle, dependencies are resolved, DOM is rendered as well as input properties are bound with data from the parent component. Angular provides this ngOnInit method especially for initial work to be done once the component is initialized. Let’s ensure this with an example,

@Component({
 selector: 'parent-component',
 template: `
    <child-component [data]="text"></child-component>
 `
})
export class ParentComponent {
 text = 'Data from parent';
constructor() { }
}
@Component({
 selector: 'child-component',
 template: `
    <p id="demo">Child Component</p>
 `
})
export class ChildComponent implements OnInit {
 @Input() data;
constructor() {
  let element = document.getElementById('demo');
  console.log('Child constructor - DOM access:', element);
  console.log('Child constructor - Input property access:', this.data);
}
ngOnInit() {
  let element = document.getElementById('demo');
  console.log('Child ngOnInit - DOM access:', element);
  console.log('Child ngOnInit - Input property access:', this.data);
  }
}

ngOnInit and ConstructorThe output shows that the DOM is rendered and input data is set before ngOnInit is invoked, indicating the component is ready for initialization.

EndNote

The constructor is a method in TypeScript whereas ngOnInit is a lifecycle hook method provided by Angular framework. To inject dependencies that are available outside the component can be done in the constructor. The logic to be executed when the component first renders on the view can be placed in ngOnInit.
I hope you find this tutorial useful! having any questions? Share them in the comments below.
Need some regular updates on Angular or more such tutorials? Subscribe to the exclusive weekly newsletter now1
Looking to develop your idea with Angular? Great choice of the framework! Don’t know how and where to start? Reach our technology experts for the guidance. We are ready to make your Angular development an innovation solution that satisfies your desires.

Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Gokulaselvan

Gokulaselvan is a software developer. He is specializing in front end frameworks such as Angular, and React. He is a passionate techie with great fondness towards problem-solving in reactive programming. You can find him browsing and exploring different trends or either searching for easier ways to solve a problem. Gokul loves to share his new learning with others.