What is the difference between the constructor and ngOnInit?
Model answer
The constructor is a TypeScript feature that runs when the class is created. In Angular it is best used only for injecting dependencies and simple field setup. At that time the inputs have not been set yet.
ngOnInit is an Angular hook that runs once after the first inputs are set. Put initial logic there, such as loading data based on an input. With inject() and signal inputs, you can often avoid ngOnInit for simple cases, but the rule is the same: do not rely on inputs in the constructor.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What are the parts of a component?
- What is data binding? Explain the four types.
- What is the difference between interpolation and property binding?
- How do you pass data from a parent component to a child component?
- How does a child component send data to its parent?
- What is the component lifecycle? Describe the main hooks.