Skip to main content
Angular Basics
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 *ngIf to conditionally render elements.
  • Use *ngFor to render lists from arrays.
  • Use *ngSwitch for multi-branch conditions.
  • Create a custom attribute directive.

3. *ngIf — Conditional Rendering

typescript
1234
export class AuthComponent {
  isLoggedIn: boolean = false;
  toggleLogin(): void { this.isLoggedIn = !this.isLoggedIn; }
}
html
123
<button (click)="toggleLogin()">Toggle Login</button>
<div *ngIf="isLoggedIn"><h2>Welcome back!</h2></div>
<div *ngIf="!isLoggedIn"><h2>Please log in.</h2></div>

4. *ngFor — Rendering Lists

typescript
123456
export class ProductListComponent {
  products = [
    { id: 1, name: &#039;Laptop&#039;, price: 999 },
    { id: 2, name: &#039;Phone&#039;, price: 599 }
  ];
}
html
12345
<ul>
  <li *ngFor="let product of products; let i = index">
    {{ i + 1 }}. {{ product.name }} — ${{ product.price }}
  </li>
</ul>

5. *ngSwitch

html
123456
<div [ngSwitch]="status">
  <p *ngSwitchCase="&#039;loading'">⏳ Loading...</p>
  <p *ngSwitchCase="&#039;success'">✅ Loaded!</p>
  <p *ngSwitchCase="&#039;error'">❌ Error!</p>
  <p *ngSwitchDefault>Unknown state.</p>
</div>

6. [ngClass] — Attribute Directive

html
1234
<div [ngClass]="{
  &#039;alert-success': alertType === 'success',
  &#039;alert-error':   alertType === 'error'
}">Alert Message</div>

7. Custom Attribute Directive

bash
1
ng g directive highlight
typescript
12345678910111213
import { Directive, ElementRef, HostListener } from &#039;@angular/core&#039;;

@Directive({ selector: &#039;[appHighlight]&#039; })
export class HighlightDirective {
  constructor(private el: ElementRef) {}

  @HostListener(&#039;mouseenter&#039;) onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = &#039;#f0f4ff&#039;;
  }
  @HostListener(&#039;mouseleave&#039;) onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = &#039;transparent&#039;;
  }
}
html
1
<p appHighlight>Hover over me to highlight!</p>

8. Modern Angular: @if and @for (v17+)

html
12345
@if (isLoggedIn) { <p>Welcome!</p> } @else { <p>Please log in.</p> }

@for (product of products; track product.id) {
  <li>{{ product.name }}</li>
}

9. Common Mistakes

  • Forgetting *: ngIf without the asterisk fails silently. Always use *ngIf.
  • No trackBy on large lists: Omitting trackBy causes 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?

Q10. Does *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 trackBy important with *ngFor for 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.

13. Next Chapter Recommendation

In Chapter 8: Pipes in Angular, we will format data directly in templates using built-in pipes for dates, currency, and uppercase, plus build custom pipes.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·