In Angular, the constructor()
is a special method used to initialize a class instance and inject dependencies, while ngOnInit()
is an Angular-specific life cycle hook that runs after the component is fully initialized, allowing for the execution of logic once bindings and properties (such as @Input
) are available. By learning the difference between constructor()
and ngOnInit()
, one can master correct dependency injection, handle asynchronous operations appropriately, optimize performance, and prevent bugs.
Key takeaways:
Use constructor()
for basic class setup and dependency injection, and ngOnInit()
for advanced initialization tasks such as fetching data or interacting with the DOM.
constructor()
is called first when a class instance is created, while ngOnInit()
is called after Angular sets up the component’s environment.
ngOnInit()
ensures that the component’s properties are fully accessible and ready for logic execution, unlike the constructor, which may not have access to certain Angular-specific properties.
The constructor()
method
The constructor()
method is derived from object-oriented programming and isn’t solely the concept of Angular. The primary function of a constructor is to create an instance of a component class. It is a default method for a class that initializes classes and subclasses and ensures proper execution of roles.
Remember that:
Whenever we call a class, we have to pass the exact match of the parameter type to the constructor of that class, e.g., Student(arg1:string, arg2:string, arg3:int)
. These arguments must be of the same type in the constructor of the Student()
class.
It runs before Angular fully initializes the components view and data bindings.
It might not have access to specific properties like @Input
values or the DOM.
Working of the constructor()
method
Constructor parameters are analyzed by Angular dependency injection. Whenever a class instance is created, the system searches for matching providers that define how to construct those dependencies. Subsequently, the resolved dependencies are then passed to similar components.
Code example
Let’s see how the constructor works: