ngOnInit vs. constructor in Angular

Today’s post is all about clarifying when to use a constructor and when to use ngOnInit to initialize data in our Angular components.

From a chronological standpoint, the constructor is called first. Then, once all component inputs are initialized, Angular is going to call ngOnInit.

From that definition, it makes sense to use ngOnInit only when your initialization code needs a @Input value to be set. Something along those lines:

And that’s the only rule. Some might be surprised to read this, but you could initialize everything in your constructor if your component has no inputs. There is no performance impact in doing one or the other.

I would argue that triggering an HTTP request in the constructor is better as it’s going to happen sooner (we’re talking milliseconds, though) than if we do it in ngOnInit.

As a result, in the absence of any official recommendation in the Angular style guide, you can choose one or the other.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.