When to use the constructor and when to use OnInit

So, I read in angular 2 that there are two ways to do the same thing, but I do not know its fundamental difference, if any.

Consider the following

Constructor

export class MyComponent {
  myAge: number;

  constructor(){
   this.myAge = 24;
  }
}

Oninit

export class MyComponent implements OnInit{
  myAge: number;

  ngOnInit(): any {
    this.myAge = 24;
  }
}
+4
source share
1 answer

The first is related to creating a 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), ...

.

+5

Source: https://habr.com/ru/post/1629778/


All Articles