Constructor Vs ngOnInit

Vaibhav Sharma
3 min readMay 3, 2019

Today we are discussing class constructor and ngOnInit. This is very frequently asked question in the interview if you are going for an Angular Developer.

Angular developer sometimes writes some code in the constructor which are related to angular and sometimes they getting undefined because constructor calls before creating the component.

Now here, we are discussing constructor and ngOnInit.

If you want to see original article, please go to The Dev Family

Constructor will call first after that ngOnInit will fire.

What is constructor :

A constructor is not the concept of Angular. It is the concept of JavaScript’s class. When you initialize the class the constructor will call every time.

When you create an object, you also initialize the constructor with the new keyword.

What is ngOnInit:

On the other hand, ngOnInit is the second stage of Angular component life cycle hook whenever is called when angular is done which creating the component.

When angular done the creating component thing then ngOnInit() will call after first ngOnChanges(). It is a good practice to initialize all the angular scope things under the ngOnInit() not under constructor.

Worng way:

If you initialize or declare the angular related code in the constructor, so you need to declare at the time of test case also. So It is the good practice to declare only those things in the constructor which are the out of scope from angular components.

Correct way :

If you use something some APIs which are under angular scope so you can write that code in ngOnInit because ngOnInit is called when a component is created and first ngOnChanges() is called.

DOM Manipulation :

If you want to some dom-manipulation related to angular in the constructor, you got undefined because all the dom-manipulation happened after calling the ngOnInit().

Any freelance work, please give me a chance

If you have any freelance work or projects. Please connect with me or drop an email at thedeveloperfamily@gmail.com.

--

--