{

How to use typescript enum in ngSwitch in angular with examples


Typescript provides grouping constants and referred to 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 expression in a programming language such as typescript or javascript.

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

Following are step by step.

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

In Angular typescript component,

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

  • Declare a variable to be used in ngSwitch expression
  • Declare a typeof enum constants 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.