4

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?

rablentain
  • 6,641
  • 13
  • 50
  • 91

1 Answers1

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 changes
  • ngOnInit is called after the first ngOnChanges

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