What is the difference between Constructor and ngOnInit

Angular Faysal Shuvo


Problem: 

We all know angular provides a life cycle hook ngOnInit by default. also, we have a constructor so why should we use ngOnInit?

So in this article, I am going to explain What is the difference between Constructor and ngOnInit.


Solution: 

Consturctor: 

When the class is instantiated the Constructor method is executed. The Constructor ensures proper initialization of the field in the class and subclasses. 

new ExampleClass(arg);

By calling new ExampleClass() a new instance creates and it tries to find providers that match the type of constructor parameters. Then it resolves them and passed them.

ngOninit:

When Angular initialized all data-bound properties of a directive this ngOninit hook is called. ngOninit() this method handles all the additional initialization tasks.

interface OnInit {
  ngOnInit(): void
}

Here is a few of the difference between constructor and ngOnInit:

1. We should use the constructor to start the class member, not for the actual work. But we use ngOnInit in every startup and try to avoid things to work in builders.

2. ngOnInit() is better where the component combination is solved and constructor() is set for only dependency injection.


Hope this solves your confusion. If you have any type of problem please comment below.