I am simply trying to figure out what the difference between the constructor and the onInit function is in a Directive in Angular2. To me both seems to be used when the object is created, so why would you not only use the constructor?
Asked
Active
Viewed 2,346 times
4
-
have a look at this http://stackoverflow.com/a/35763811/5043867 – Pardeep Jain Mar 12 '16 at 16:00
1 Answers
3
The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.
The second one corresponds to a lifecycle hook of Angular2 components:
ngOnChanges
is called when an input or output binding value changesngOnInit
is called after the firstngOnChanges
So you should use ngOnInit
if initialization processing relies on bindings of the component (for example component parameters defined with @Input
), otherwise the constructor would be enough...

Thierry Templier
- 198,364
- 44
- 396
- 360
-
-
For example if you want to use injected objects without setting them as class properties... – Thierry Templier Feb 28 '16 at 09:53
-
Injection is done at the constructor level. But using ngOnInit for other initializations is fine ;-) – Thierry Templier Feb 28 '16 at 10:10