ngSwitch in Angular
Written By: Avinash Malhotra
Updated on
ngSwitch
NgSwitch directive is used for Switch Case. [ngSwitch] directive is used in parent container with the matched value. ngSwitchCase is used for multiple cases inside ngSwitch container.
If no case is matched, use ngSwitchDefault for default case.
ngSwitch Example
Monday
<!-- app.component.ts -->
export class AppComponent {
days=2;
}
<!-- app.component.html -->
<div [ngSwitch]="day">
<p *ngSwitchCase="1">Sunday</p>
<p *ngSwitchCase="2">Monday</p>
<p *ngSwitchCase="3">Tuesday</p>
<p *ngSwitchCase="4">Wednesday</p>
<p *ngSwitchCase="5">Thursday</p>
<p *ngSwitchCase="6">Friday</p>
<p *ngSwitchCase="7">Saturday</p>
<p *ngSwitchDefault>Invalid Day</p>
</div>
@switch
@switch block introduced in Angular 17. It is the replacement of ngSwitch in Angular 17 and above. @default can also be used for default in switch.
Monday
<!-- app.component.ts -->
export class AppComponent {
day=2;
}
@switch (days) {
@case (day==1){ <p>Sunday</p>}
@case (day==2){ <p>Monday</p>}
@case (day==3){ <p>Tuesday</p>}
@case (day==4){ <p>Wednesday</p>}
@case (day==5){ <p>Thursday</p>}
@case (day==6){ <p>Friday</p>}
@case (day==7){ <p>Monday</p>}
@default { <p>Invalid Day</p> }
}
ngSwitchDefault
ngSwitchDefault is used as default in switch case. If no case is matched, it will print the fallback message.
Invalid Day
<!-- app.component.ts -->
export class AppComponent {
day=8;
}
<!-- app.component.html -->
<div [ngSwitch]="day">
<p *ngSwitchCase="1">Sunday</p>
<p *ngSwitchCase="2">Monday</p>
<p *ngSwitchCase="3">Tuesday</p>
<p *ngSwitchCase="4">Wednesday</p>
<p *ngSwitchCase="5">Thursday</p>
<p *ngSwitchCase="6">Friday</p>
<p *ngSwitchCase="7">Saturday</p>
<p *ngSwitchDefault>Invalid Day</p>
</div>