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.