Angular Quick Answer: Difference between constructor and ngOnInit

Who would-a guessed..

That…

One of the most popular Angular questions on Stack Overflow…

Is a question about the difference between Angular’s constructor and the OnInit function?

Here’s the quick answer.

The constructor is a Typescript feature used to instantiate the Typescript class. In most Angular projects about the only thing that should ever be done in the constructor is to inject services.

The ngOnInit function is specific to the Angular framework and is called when Angular is done creating the component. It should be called with any custom finalization like loading data for your component to display.

You still around?

Oh! So you want to know more.

What is the constructor?

A Typescript constructor is a simple function that is declared inside of a class.

Like this.

It automatically gets called when we create a new instance of our class.

Since the constructor is a Typescript feature it’s important to realize that there is no relationship between Angular and the constructor. Normally, you will use the constructor to define or initialize some variables. A good example of this is dependency injection as show in action below.

In this example, we use the constructor to inject Angular’s HTTP client.

What is the ngOnInit function?

The ngOnInit function is specific to Angular applications.

It is called as soon as Angular has finished initializing our component. Which allows us to finish initializing the component however we dandy-well please. For example, this is where you will call functions to load external data, etc…

Any real work should always be placed in the ngOnInit method.

According to the Angular docs, components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method.

Still doubtful about the difference?

Maybe you’re still confused about the difference between the constructor and ngOnInit?

Or some of the terminology that I used?

Or maybe there’s a way to explain this better?

Let me know in the comments below.

For now, I’ve gotta go work on my coffee spewer. 👋

Follow Me: GitHub, Medium, Personal Blog

Angular Consultant

Originally published at https://danielk.tech.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store