What is the difference between the constructor and ngOnInit?

Angular components and templates · Freshers and experienced

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