Add Switch Case in Angular 13 Component Class TS file

When you have a number of conditional expressions to evaluate, then you can use the IF-ELSE or Switch case statements. Adding a Switch case make the code more readable and easy to maintain. For this reason, most of the developers use Switch over IF-ELSE to make their code look compact and more graceful.

In this tutorial, you will learn how to add a Switch case expression in Angular application using the TypeScript coding standards.

TLDR;

For those who are in hurry 🙂

switch (valueType) {
      case 'add-only-height':
        this.addHeight(value);
        break;

      case 'add-only-width':
        this.addWidht(value);
        break;

      default:
        this.addHeight(value);
        this.addWidht(value);
        break;
}

You can also wrap each case around braces {} to leverage the block scope. For example, you can use let or const variables inside each case with their own block scope.

switch (valueType) {
      case 'add-only-height': {
        let offset_h = 3;
        this.addHeight(value+offset_h);
        break;
      }

      case 'add-only-width': {
        let offset_w = 3;
        this.addWidht(value+offset_w);
        break;
      }
      default: {
        this.addHeight(value);
        this.addWidht(value);
        break;
      }
    }

 

Example of a Switch statement in Component class function:

 

maintainDimentions(valueType: string, value: number) {
    switch (valueType) {
      case 'add-only-height':
        this.addHeight(value);
        break;

      case 'add-only-width':
        this.addWidht(value);
        break;

      default:
        this.addHeight(value);
        this.addWidht(value);
        break;
    }
  }

  addHeight(value: number) {
    // Increase Height
  }
  addWidht(value: number) {
    // Increase Widht
  }

 

The above function can be called from HTML template as shown below:

<button (click)="maintainDimentions('add-only-height',10)">Height</button>
<button (click)="maintainDimentions('add-only-width',10)">Width</button>
<button (click)="maintainDimentions('both',10)">Both</button>

 

This is a quick and handy example of Switch case statement usage in the TypeScript Class that we use in Angular components.

 

Leave a Reply

Your email address will not be published. Required fields are marked *