Return to site

ANGULAR INTERVIEW QUESTION: What is the difference between the constructor and the ngOnInit?

· ngInterview,fullstack

Let's define each of them:

―The constructor is the default method executed when the class is instantiated.

Generally, in programming, its purpose is to guarantee the correct initialization of the class attributes.

But in Angular, its role is only to configure the dependencies injection.

―NgOnInit is a lifecycle method of Angular that is called only when the component is correctly initialized, and the property binding is done.

The lifecycle method NgOnInit is the best place to interact with your template at component startup because you're sure the property binding is done correctly.

 

 

𝐓𝐨 𝐬𝐮𝐦 𝐮𝐩, 𝐭𝐡𝐞 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐡𝐚𝐧𝐝𝐥𝐞𝐬 𝐭𝐡𝐞 𝐝𝐞𝐩𝐞𝐧𝐝𝐞𝐧𝐜𝐢𝐞𝐬 𝐢𝐧𝐣𝐞𝐜𝐭𝐢𝐨𝐧, 𝐚𝐧𝐝 𝐭𝐡𝐞 𝐍𝐠𝐎𝐧𝐈𝐧𝐢𝐭 𝐝𝐞𝐟𝐢𝐧𝐞𝐬 𝐭𝐡𝐞 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐚𝐭 𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧.