1

I know ngOnInit is Angular specific syntax while constructor is Typescript/ES2015 class syntax. But when it come to their usage and execution in Angular 2 Components what are the differences?

Rohit Rane
  • 2,790
  • 6
  • 25
  • 41
  • 3
    Possible dup of http://stackoverflow.com/questions/35763730/what-is-the-difference-between-constructor-and-ngoninit?rq=1 – yurzui Sep 19 '16 at 06:09

1 Answers1

2

The constructor is called when the class instance is created by Angulars DI.

ngOnInit() is a lifecycle hook that is called later by Angular2 change detection. When @Input()s are updated by change detection, ngOnChanges(changes) is called. After ngOnChanges(changes) was called the first time ngOnInit() is called.

The main difference is therefore, that change detection has been run and that @Input()s are initialized.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567