Angular Directives & Control Flow — Interview Quick Revision
1. What is a directive in Angular?
A directive is a class that adds or changes the behavior, appearance, or structure of DOM elements.
Custom directives are created using the @Directive decorator.
2. What are the different types of directives?
Traditionally, Angular directives are classified as Component, Attribute, and Structural directives.
Examples: Component, ngClass, *ngIf.
3. What is a component directive?
A component is a special type of directive that has its own HTML template.
It is created using @Component, which extends directive capabilities with a view.
4. What is an attribute directive?
An attribute directive changes the appearance or behavior of an existing element without changing the DOM structure.
Examples: ngClass, ngStyle, and custom highlight directives.
5. What is a structural directive?
A structural directive changes the DOM structure by adding, removing, or repeating elements.
Traditional examples: *ngIf, *ngFor, and *ngSwitchCase.
6. How were *ngIf, *ngFor, and *ngSwitch traditionally used?
They provided conditional rendering, iteration, and selection using Angular's traditional structural-directive syntax.<div *ngIf="isLoggedIn">Welcome</div> / <li *ngFor="let p of products">{{ p.name }}</li>
7. What are Angular's modern control-flow blocks?
Modern Angular provides built-in control-flow syntax directly in templates.
The main blocks are @if, @for, and @switch.
8. What are @if, @for, and @switch?
@if handles conditions, @for iterates collections, and @switch handles multiple conditions.@if (isLoggedIn) { <p>Welcome</p> }
9. What is the difference between *ngIf and @if?
*ngIf is the older structural-directive syntax; @if is the modern built-in control-flow syntax.
Old: <div *ngIf="show">Hi</div> → Modern: @if (show) { <div>Hi</div> }
10. What is the difference between *ngFor and @for?
*ngFor is the traditional structural directive; @for is the modern built-in loop syntax.
Old: *ngFor="let p of products" → Modern: for (p of products; track p.id) { ... }
11. What is track in an @for block?
track tells Angular how to uniquely identify items so it can efficiently update the DOM instead of recreating elements unnecessarily.@for (product of products; track product.id) { {{ product.name }} }
12. How do you create a custom directive?
Create a class with the @Directive decorator and define a selector. Modern directives can be standalone.@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { }