Angular Quick Answer: Difference between constructor and ngOnInit
Who would-a guessed..
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.
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.
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?
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
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
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. 👋
Originally published at https://danielk.tech.