What is the difference between constructor and ngOnInit?

TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method. In order to use ngOnInit, you need to implement OnInit interface as below,

export class App implements OnInit {
constructor() {
//called first time before the ngOnInit()
}
ngOnInit() {
//called after the constructor and called after the first ngOnChanges()
}
}

Author of content
Edit this page

Made by Michael Sakhniuk

Twitter