Question presented to candidate: "What is a directive in Angular? Walk me through the different types, give an example of each, and tell me when you would write your own."
What a strong answer should cover:
- A directive is a class with
@Directivemetadata that Angular attaches to elements matching its selector, to add behaviour or change appearance. - Components are directives with a template (
@Componentextends@Directive). - Attribute directives change the look or behaviour of their host element (
NgClass,NgStyle,NgModel, a customappHighlight), typically throughhostbindings and listeners. - Structural directives add or remove DOM by stamping out an
ng-templateviaTemplateRefandViewContainerRef(*ngIf,*ngFor, custom*appHasRole); the built-in three are now replaced by@if/@for/@switch. - Host directives (directive composition API, v15+) let a component or directive apply other directives to its own host without inheritance.
- Directives are standalone by default and must be imported where used.
Clarifying questions expected:
- "Do you want the conceptual categories, or how to build one?"
Code / implementation expected: Yes — a custom attribute directive, ideally also a structural one.