Angular: Please explain diff between Constructor and ngOnInit()

curiouswebster
curiouswebster used Ask the Experts™
on
Angular: Please explain diff between Constructor and ngOnInit()

What kinds of things are done in either function?

hanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
The constructor is implemented by Typescript and it runs when the class is instantiated. Angular analyses the constructor and looks for dependencies that must be injected into the constructor. Use this to inject dependencies.

When the TS transpiled into JavaScript it creates a function for the class - which is called irrespective of whether you declared a constructor in the TS source.

ngOnInit runs when Angular is finished creating the component.

You can read more about it here https://blog.angularindepth.com/the-essential-difference-between-constructor-and-ngoninit-in-angular-c9930c209a42
curiouswebsterSoftware Engineer

Author

Commented:
thanks
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial