Interview Questions

1. What is the key difference between a constructor and ngOnInit?

Constructor is a default method in TypeScript classes that are normally used for initialization purpose. On the other hand, the ngOnInit is specifically an Angular method and is used to define Angular bindings. Even though constructors are getting called first, it is always preferred to move all of your Angular bindings to the ngOnInit method.

See the following example of how we can use ngOnInit by implementing the OnInit interface as follows:

export class App implements OnInit{  

  constructor(){  

     //called first time before the ngOnInit()  

  }  

  ngOnInit(){  

     //called after the constructor and called  after the first ngOnChanges()  

  }  

}  

By Md Riyazuddin 2 0
Is this helpful? Yes No

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of w3Sniff.

Get Started

Comments

Leave a Comment


Check out more interview questions

Based on your skills

MS SQL Server

1636343 1720 22 859

Angular

41369 92 0 46

Wordpress

33547 72 1 36