Directives Introduction
Understand Angular directives — structural directives (ngIf, ngFor, ngSwitch) and attribute directives.
Directives Introduction
Directives are instructions in the DOM. They tell Angular to do something to a DOM element — add/remove it, repeat it, change its appearance, or modify its behavior.
Types of Directives
| Type | What It Does | Examples |
|---|---|---|
| Components | Directives with a template | @Component |
| Structural | Change the DOM structure (add/remove elements) | *ngIf, *ngFor, *ngSwitch |
| Attribute | Change the appearance/behavior of an element | ngClass, ngStyle, custom directives |
*ngIf — Conditional Rendering
<!-- Show/hide based on a condition -->
<div *ngIf="isLoggedIn">
<h2>Welcome, {{ username }}!</h2>
<button (click)="logout()">Logout</button>
</div>
<!-- With else -->
<div *ngIf="isLoggedIn; else loginBlock">
<p>Welcome back!</p>
</div>
<ng-template #loginBlock>
<p>Please <a routerLink="/login">sign in</a>.</p>
</ng-template>
*ngIf removes the element from the DOM when false — not just hiding it. The component is destroyed and recreated.
*ngFor — Repeating Elements
<ul>
<li *ngFor="let item of items; let i = index">
{{ i + 1 }}. {{ item }}
</li>
</ul>
We'll cover *ngFor in detail in the next episode.
*ngSwitch — Multiple Conditions
<div [ngSwitch]="userRole">
<p *ngSwitchCase="'admin'">Full access dashboard</p>
<p *ngSwitchCase="'editor'">Content management</p>
<p *ngSwitchCase="'viewer'">Read-only access</p>
<p *ngSwitchDefault>Unknown role</p>
</div>
Attribute Directives
<!-- ngClass — dynamic CSS classes -->
<div [ngClass]="{ 'active': isActive, 'error': hasError }">
Content
</div>
<!-- ngStyle — dynamic inline styles -->
<div [ngStyle]="{ 'color': textColor, 'font-size': size + 'px' }">
Styled
</div>
Structural vs Attribute
| Feature | Structural (*) | Attribute |
|---|---|---|
| Prefix | * (asterisk) | No prefix (uses []) |
| Effect | Adds/removes DOM elements | Changes appearance/behavior |
| Limit | One per element | Multiple per element |
| Examples | *ngIf, *ngFor | ngClass, ngStyle |
Key Takeaways
- Directives are instructions that modify the DOM
- Structural directives (
*) add or remove elements - Attribute directives change element appearance or behavior
*ngIfconditionally renders elements*ngSwitchhandles multiple conditions like a switch statement- You can only have one structural directive per element