Back to all posts

Angular: Structural directives (if, for and switch)


In angular template we can manage conditional rendering by using Structural directives. Let’s see how can we do that with code.

Using *ngIf and *ngFor

Before Angular 16, developer relied on structural directives like *ngIf and *ngFor for template logic.

Conditional Rendering with *ngIf

The *ngIf directive dynamically includes or excludes elements in the DOM based on a condition.

<div *ngIf="isLoggedIn; else loggedOut">
  <p>Welcome back, User!</p>
</div>
<ng-template #loggedOut>
  <p>Please log in to continue.</p>
</ng-template>

Iteration with *ngFor

The *ngFor directive is used to iterate over a collection and render its elements.

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

Multi-Case with *ngSwitch

The *ngSwitch directive dynamically displays elements based on a single condition. It works alongside *ngSwitchCase and *ngSwitchDefault to handle various cases.

<div [ngSwitch]="status">
  <p *ngSwitchCase="'active'">The status is active.</p>
  <p *ngSwitchCase="'inactive'">The status is inactive.</p>
  <p *ngSwitchCase="'pending'">The status is pending.</p>
  <p *ngSwitchDefault>The status is unknown.</p>
</div>

Modern Approach:

Angular 16 introduces @if and @for, bringing a cleaner and more intuitive syntax to templates.

Conditional Rendering with @if

The @if syntax simplifies conditional rendering without needing separate ng-template elements.

@if (isLoggedIn) {
  <p>Welcome back, User!</p>
} @else {
  <p>Please log in to continue.</p>
}

Iteration with @for

Similarly, @for makes iterating over collections more concise and readable.

@for (let item of items) {
  <li>{{ item }}</li>
}