bluehost-banner
Difference between Constructor and ngOnInit in Angular

Difference between Constructor and ngOnInit in Angular

In this article, we will see the difference between Constructor and ngOnInit in Angular.

Constructor

The Constructor is not actually part of Angular, it is a feature of TypeSciprt class, which is called when the class is instantiated.

Constructor is used to create a new instance of the class.

The constructor will be automatically invoked by the JavaSscprt engine.

In Angular, the constructor is used for injecting dependencies into the component class.

While writing the code try to keep the constructor as simple as possible, so Unit Testing can be very easy if the constructor logic is simple.

NgOnInit

Every componenet we create has a life cycle managed by Angular.

The NgOnInt is a life cycle hook managed by Angular.

Whenever you create a new component using angular-CLI ngOnint is added by default.

NgOnint will be called after the constrcor execution and after first NgOnchanges

NgOnInit() is called by Angular to indicate that Angular is done with initializing the component.

The NgonInit is called after the constrcor is executed.In Constrcor Angular initlizes ans resolve all class memebers so in NgonInit you can initilize work and logic the componenent.

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment