Skip to main content

Angular 17 switch case Example | @switch block selection | @default block

B Built-in control flow and the NgIf, NgSwitch and NgFor structural directives:

1.     The @if block replaces *ngIf for expressing conditional parts of the UI.

2.     The @switch block replaces ngSwitch with major benefits.

3.     The @for block replaces *ngFor for iteration, and has several differences compared to its structural directive NgFor predecessor.

4.     The track setting replaces NgFor's concept of a trackBy function.

The improved ergonomics is even more visible with *ngSwitch:

The new control flow enables significantly better type-narrowing in the individual branches in @switch, which is impossible in *ngSwitch.

Before Angular 17,

<div [ngSwitch]="accessLevel">

  <admin-dashboard *ngSwitchCase="admin"/>

  <moderator-dashboard *ngSwitchCase="moderator"/>

  <user-dashboard *ngSwitchDefault/>

</div>


From Angular 17: 

Which with the built-in control flow turns into the @switch block - selection

The syntax for @switch is very similar to @if statement. See what the basic looks like:

@switch (condition) {

  @case (caseA) {

    Case A.

  }

  @case (caseB) {

    Case B.

  }

  @default {

    Default case.

  }

}

The value of the conditional expression is compared to the case expression using the === operator.

The @switch does not have fall through, so you do not need an equivalent to a break or return statement.

The @default block is optional and can be omitted. If no @case matches the expression and there is no @default block, nothing is shown.


See the example with Access Level:

@switch (accessLevel) {

  @case ('admin') { <admin-dashboard/> }

  @case ('moderator') { <moderator-dashboard/> }

  @default { <user-dashboard/> }

}