Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

15. What is the difference between constructor and ngOnInit? #41

Closed
ic3top opened this issue Jul 10, 2022 · 2 comments
Closed

15. What is the difference between constructor and ngOnInit? #41

ic3top opened this issue Jul 10, 2022 · 2 comments

Comments

@ic3top
Copy link
Contributor

ic3top commented Jul 10, 2022

  1. I don't think the answer was given at all.
  2. The statement it is preferred to move all of your Angular bindings to ngOnInit method is wrong, constructor has its own job as well as ngOnInit.

I think this answer is more applicable:

Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular is preferably the Dependency Injector (DI), analyzes the builder’s components and when creating a new feature by calling the new MyClass() tries to find suppliers that match the builder’s parameter types, resolve them and pass them to similar components.

ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create a component.

Differences:
We use constructor() for all the initialization/declaration.
It’s better to avoid writing actual work in the constructor.
The constructor() should only be used to initialize class members but shouldn’t do actual “work”.
So we should use constructor() to set up Dependency Injection, Initialization of class fields, etc.
ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.
Like loading data from Database — to show the user in your HTML template view. Such code should be written in ngOnInit().

@sudheerj
Copy link
Owner

Thank you for the question @ic3top Can you create it as PR?

@ic3top
Copy link
Contributor Author

ic3top commented Jul 31, 2022

Sure, here you go #43

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants