CHAPTER 07
Beginner
Directives in Angular
Updated: May 18, 2026
5 min read
# CHAPTER 7
Directives in Angular
1. Chapter Introduction
Directives are special instructions that tell Angular to modify the DOM. Structural Directives modify the layout by adding or removing elements. Attribute Directives change the appearance or behavior of existing elements.2. Learning Objectives
-
Use
*ngIfto conditionally render elements.
-
Use
*ngForto render lists from arrays.
-
Use
*ngSwitchfor multi-branch conditions.
- Create a custom attribute directive.
3. *ngIf — Conditional Rendering
typescript
html
4. *ngFor — Rendering Lists
typescript
html
5. *ngSwitch
html
6. [ngClass] — Attribute Directive
html
7. Custom Attribute Directive
bash
typescript
html
8. Modern Angular: @if and @for (v17+)
html
9. Common Mistakes
-
Forgetting
*:ngIfwithout the asterisk fails silently. Always use*ngIf.
-
No
trackByon large lists: OmittingtrackBycauses full list re-renders on every change.
10. MCQs with Answers
Question 1
What is the role of a Structural Directive?
Question 2
Which directive conditionally renders an element?
Question 3
Which directive renders a template for each item in an array?
Question 4
How do you get the index in *ngFor?
Question 5
When is *ngSwitch preferred over *ngIf?
Question 6
What does [ngClass] do?
Question 7
What decorator marks a class as a directive?
Question 8
What is @HostListener used for?
Question 9
In Angular 17+, what replaces *ngIf?
*ngIf="false" hide or remove the element?
a) Hides with CSS b) Completely removes from DOM
Answer: b) Completely removes from DOM.
11. Interview Questions
- Q: Difference between a Structural Directive and an Attribute Directive?
-
Q: Why is
trackByimportant with*ngForfor performance?
12. Summary
Directives extend HTML with Angular superpowers.*ngIf provides conditional rendering, *ngFor generates repeated elements from data arrays, and custom directives encapsulate DOM manipulation logic cleanly.