Angular2 directive, constructor vs onInit

I'm just trying to figure out what the difference between the constructor and the onInit function is in the directive in Angular2. It seems to me that both are used when the object is created, so why not just use the constructor?

+4
source share
1 answer

The first (constructor) is associated with an instance of the class and has nothing to do with Angular2. I mean, the constructor can be used for any class. You can add some initialization processing to the newly created instance.

The second corresponds to the Angular2 component lifecycle hook:

  • ngOnChanges called when the input or output binding value changes
  • ngOnInit called after the first ngOnChanges

, ngOnInit, (, , @Input), ...

+3

All Articles