How to use typescript enum in ngSwitch in angular with examples

Typescript provides grouping constants and is referred to as the enum type.

export enum Day {

  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY,
}

Enum constants only exist at compile-time, So javascript does not have a concept of enum types.

Sometimes, We want to map enum constants with angular ngSwitch in an HTML template.

ngSwitch is used to select one element from multiple ngSwitchCase in Angular templates.

It is similar to switch case expressions in a programming language such as typescript or javascript.

How to use typescript enum in Angular ngSwitch and ngSwitchCase with examples

The following are step by step.

  • Let’s declare an enum in day.ts
export enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

In the Angular typescript component,

Since the enum class is directly not used in the HTML template, SO you have to declare the below things

  • Declare a variable to be used in the ngSwitch expression
  • Declare a typeof enum constant and used it in ngSwtichCase

Here is an angular typescript component

import { Component } from "@angular/core";
import { Day } from "./day";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  day: typeof Day;

  constructor() {
    this.day = Day;
  }

  sunday = Day.SUNDAY;
}

In the template component, Declare ngSwitch, ngSwitchCase, and ngSwitchDefault and use those variables in expressions and case statements.

<div class="info-card" [ngSwitch]="sunday">
  <div *ngSwitchCase="this.day.SUNDAY">Today is sunday</div>
  <div *ngSwitchCase="this.day.MONDAY">Today is monday</div>
  <div *ngSwitchCase="this.day.TUESDAY">Today is tuesday</div>
  <div *ngSwitchCase="this.day.WEDNESDAY">Today is wednesday</div>
  <div *ngSwitchCase="this.day.THURSDAY">Today is thursday</div>
  <div *ngSwitchCase="this.day.FRIDAY">Today is friday</div>
  <div *ngSwitchCase="this.day.SATURDAY">Today is saturday</div>
  <div *ngSwitchDefault>Default case</div>
</div>

Conclusion

To summarize, Declared enum constants in typescript and use an enum to map with angular ngSwitch case with examples.