Overview:
If you are new to angular or have been working with it for a while, you will have questions like:
Is it necessary to inject dependencies in the constructor and bind data? When should we use ngOnInit ? What is the difference between constructor and OnInit?. So, in this blog we will answer all these questions. Before we begin It is important to know that constructor is not an angular feature, but is a feature of class (typescript) itself;it is also known as an object-oriented design concept.
constructor:
The constructor is part of a javascript class or typescript class. constructor is a default method of class that is executed when class is instantiated.It is where we would initialize a new instance. Dependency Injector (DI) in angular analyzes the constructor parameters.
Angular components can grow in size and complexity, which means we want to inject many dependencies and declare properties and bind observables. constructor is an ideal place to inject, but not handle the wiring up.
This will bind ActivatedRoute to the class making it accessible as a part of the component via this.route .
constructor is a place where we wire up our dependencies and leave it as clean as possible. The constructor is not called by angular directly, so it is not easy to test. Angular will not have any control over when this constructor is called. So this leads us to use a lifecycle hook ngOnInit, which fires as soon as the angular component is ready.
Lifecycle hooks:
Lifecycle hooks are just methods on a class that describes key points in time. Some Lifecycle hooks which Angular provides are OnInit, OnDestroy, OnChanges etc..
When a Component is created in angular, the OnChanges Lifecycle hook actually is called first. The next Lifecycle hook that is called is OnInit hook.
ngOnInit can be declared as a method after importing the OnInit interface . implements are used to give us some type safety.
The above approach makes unit testing easier as we can control the lifecycle hook. The ngOnInit lifecycle hook is a perfect place to create more complex logic and initializing of the component.
Above is what technically happens when angular instantiates our component and invokes ngOnInit.
The ngOnInit Lifecycle hook is the perfect place to wire up observables, talk to services and make any request we need. Another very important aspect is , ngOnInit is called by angular exactly when the components @Input() properties are ready.
In the above example, username is undefined inside the constructor whereas @input() properties are available inside ngOnInit.