Constructor Vs ngOnInit : Angular Components

Fikayo Adepoju
2 min readSep 11, 2017

--

This article is one in a series of articles inspired by my latest hobby which is explaining Angular (Angular 2+) concepts in short articles, avoiding all the mumbo jumbo.

In this article, I will be discussing a few considerations to take note of when working with Angular Components and that is how to use the constructor function and the ngOnInit function.

The constructor Function

The constructor function comes with every class, constructors are not specific to Angular but are concepts derived from Object oriented designs. The constructor creates an instance of the component class.

The ngOnInit Function

The ngOnInit function is one of an Angular component’s life-cycle methods. Life cycle methods (or hooks) in Angular components allow you to run a piece of code at different stages of the life of a component.

Unlike the constructor method, ngOnInit method comes from an Angular interface (OnInit) that the component needs to implement in order to use this method. The ngOnInit method is called shortly after the component is created.

What to consider

For most people coming with a good background in Object Oriented programming, it makes sense to insert dependencies into the constructor and also put all the component initialization code inside the constructor body. While the former works fine, the latter results in an Angular gotcha when you realize that all your initialization code placed in the constructor body is not executed.

This is because the constructor is called to initialize the class and not the component. The constructor is called before ngOnInit , at this point the component hasn’t been created yet, only the component class has being instantiated thus your dependencies are brought in, but your initialization code will not run.

To ensure your initialization code runs, simply put it in the ngOnInit function which guarantees you that the component has already being created.

So to wrap things up, while coding your components, inject your dependencies into the component class constructor method but put all your initialization code in your ngOnInit life cycle method.

There you have it, another simple Angular mystery cleared up.

Happy coding :)

--

--

Fikayo Adepoju
Fikayo Adepoju

Written by Fikayo Adepoju

@LinkedIn Author | Technical Writer | Software Developer

Responses (3)