InterviewHubPRO
Section Overview
Q22

Question 22 of 283

Part 1: Architecture, Components, Directives & Lifecycle (1 - 35)

8%
Angular & Signals (283 Qs)•Part 1: Architecture, Components, Directives & Lifecycle (1 - 35)

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:

html
<!-- 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:

html
<!-- 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

FeatureClassic *ngIf DirectiveModern @if Built-in Block
Imports RequiredRequires CommonModule or NgIf⚡ Zero imports
Else BranchingRequires <ng-template #ref> boilerplateIntuitive @else { ... } block
Else-If ChainingClunky nesting of multiple *ngIf containersNative @else if (condition) { ... }
Type NarrowingBasic type narrowingAdvanced automatic TypeScript type narrowing across branches
DOM BehaviorAdds/removes element from DOM treeAdds/removes element from DOM tree (optimized AST)