What is the purpose of *ngIf directive?
Angular provides conditional rendering to show or hide portions of the DOM based on a truthy/falsy condition. You can implement conditional rendering using the Classic Built-in Structural Directive (*ngIf) or the modern Built-in Control Flow (@if) introduced in Angular 17+.
1. Classic Built-in Syntax: *ngIf Directive
The *ngIf directive conditionally adds or removes elements from the DOM. An optional else clause references an <ng-template> element via a template reference variable:
<!-- Classic *ngIf with else template (requires CommonModule or NgIf import) -->
<div *ngIf="isLoggedIn; else loginPrompt">
<p>Welcome back, {{ currentUser.name }}!</p>
<button (click)="logout()">Sign Out</button>
</div>
<ng-template #loginPrompt>
<p>Please log in to continue.</p>
<button (click)="login()">Sign In</button>
</ng-template>
2. Modern Built-in Control Flow: @if Block (Angular 17+)
The modern @if control flow replaces the verbose <ng-template> else pattern with intuitive JavaScript-like control blocks, supporting @else if and @else natively:
<!-- Modern Built-in Control Flow syntax (Angular 17+) -->
@if (isLoggedIn) {
<p>Welcome back, {{ currentUser.name }}!</p>
<button (click)="logout()">Sign Out</button>
} @else if (isGuest) {
<p>Browsing as guest. Some features are restricted.</p>
<button (click)="login()">Upgrade Account</button>
} @else {
<p>Please log in to continue.</p>
<button (click)="login()">Sign In</button>
}
3. Side-by-Side Comparison: Classic vs Built-in Control Flow
| Feature | Classic *ngIf Directive | Modern @if Built-in Block |
|---|---|---|
| Imports Required | Requires CommonModule or NgIf | ⚡ Zero imports |
| Else Branching | Requires <ng-template #ref> boilerplate | Intuitive @else { ... } block |
| Else-If Chaining | Clunky nesting of multiple *ngIf containers | Native @else if (condition) { ... } |
| Type Narrowing | Basic type narrowing | Advanced automatic TypeScript type narrowing across branches |
| DOM Behavior | Adds/removes element from DOM tree | Adds/removes element from DOM tree (optimized AST) |