What are directives in Angular?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Angular development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Directives are classes that add behavior to DOM elements or transform DOM layout. Three types: (1) Component directives: components ARE directives with a template (the most common type); (2) Structural directives: change the DOM structure by adding, removing, or manipulating elements. Prefixed with * (syntactic sugar for <ng-template>). Built-in: *ngIf: <div *ngIf="isLoggedIn; else loginTemplate"> — conditionally includes/removes an element; *ngFor: <li *ngFor="let item of items; let i = index; trackBy: trackById"> — repeats an element for each item in a list; *ngSwitch: conditionally display one of several views. New syntax (Angular 17+): @if, @for, @switch control flow; (3) Attribute directives: change the appearance or behavior of an existing element. Built-in: ngClass: [ngClass]="{ active: isActive, error: hasError }"; ngStyle: [ngStyle]="{ color: textColor, fontSize: fontSize + 'px' }"; ngModel: two-way binding; Custom attribute directive example: create a directive that turns text yellow on hover. Creating a directive: ng generate directive highlight — class with @Directive({ selector: '[appHighlight]' }) decorator. Access the host element via ElementRef and Renderer2 (DOM manipulation).
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Angular codebase.