NgSwitch with an enum

In our previous example we used the NgSwitch directive in Angular with hard coded string values. This is not very practical. Rather, we can specify an expression to each NgSwitchCase directive that is evaluated against the expression that is provided to the NgSwitch root directive. This is well suited for an enumeration with TypeScript.

Enumerations in TypeScript

If you're new to TypeScript, or come from a pure JavaScript background, you may not be familar with enumerations. An enumeration, or just an "enum" for short, is simply a type that is declared where each member represents a unique state. Here is an example of an enum of colors:

enum Colors {

In this case the enum represents three distinct colors. When we do not explicitly set a value for each member they inherit an integer value, incrementing from 0. The follow enum explicitly sets the value for each member and is identical to the enum above:

enum Colors {
  Red = 0,
    White = 1,
    Blue = 1

We can also specify a string value for an enum in TypeScript:

enum Colors {
  Red = 'red',
    White = 'white',
    Blue = 'blue'

Using an enum with the NgSwitch directive

Here was our previous example of an NgSwitch where we used hard-coded string values:

<div [ngSwitch]="person.department">
  <span *ngSwitchCase="'Engineering'">Software Engineering</span>
  <span *ngSwitchCase="'Testing'"> QA</span>
  <span *ngSwitchCase="'Marketing'">Marketing and Sales</span>

We can refactor this to use an enumeration. First, declare a new Department enum:

export enum Department {
  Engineering = 'Engineering',
    Testing = 'Testing',
    Marketing = 'Marketing'

We can now reference the enum value in each of the NgSwitchCase directive:

<div [ngSwitch]="person.department">
  <span *ngSwitchCase="Department.Engineering">Software Engineering</span>
  <span *ngSwitchCase="Department.Testing"> QA</span>
  <span *ngSwitchCase="Department.Marketing">Marketing and Sales</span>

This is much cleaner as we are not using "magic" hard-coded strings in our templates and are referencing the single Department enumeration type.


I finished! On to the next chapter