Return to site

ANGULAR INTERVIEW QUESTION: What is the difference between an Angular component and a directive?

· ngInterview,fullstack

A component is a class with the @Component decorator whose job is to create a view with a specific behavior, which will be added to the DOM elements hierarchy of the Angular app GUI.🎨

A directive is a class with the @Directive decorator. It does not has view (no HTML template), and only add a specific behavior to the DOM or to a component instance (in order to reuse it in multiple locations).🔧


So you create a component when you want to add an element to the GUI DOM.

And you do a directive when you want to define a reusable behavior, to strengthen the already existing elements of your DOM.


𝐓𝐨 𝐬𝐮𝐦-𝐮𝐩:

𝐂𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭 = 𝐕𝐢𝐞𝐰 + 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫

𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐯𝐞 = 𝐑𝐞𝐮𝐬𝐚𝐛𝐥𝐞 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫