← Back to all tutorials

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

TypeWhat It DoesExamples
ComponentsDirectives with a template@Component
StructuralChange the DOM structure (add/remove elements)*ngIf, *ngFor, *ngSwitch
AttributeChange the appearance/behavior of an elementngClass, 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

FeatureStructural (*)Attribute
Prefix* (asterisk)No prefix (uses [])
EffectAdds/removes DOM elementsChanges appearance/behavior
LimitOne per elementMultiple per element
Examples*ngIf, *ngForngClass, ngStyle

Key Takeaways

  • Directives are instructions that modify the DOM
  • Structural directives (*) add or remove elements
  • Attribute directives change element appearance or behavior
  • *ngIf conditionally renders elements
  • *ngSwitch handles multiple conditions like a switch statement
  • You can only have one structural directive per element