Two switch case values in angular

Here's a variation that combines Fabio's second answer with brian3kb's to produce a more condensed solution without obfuscating meaning.

If there are multiple matches for a case it uses array.includes() instead of comparing each option individually.

It is especially useful if there are more than two matches as it will be much more condensed relative to the accepted answer.

<div [ngSwitch]="data.type">
   <div *ngSwitchCase="['multi-choice', 'singe-choice'].includes(data.type) ? data.type : ''">FORM 1</div>
   <div *ngSwitchCase="'range'">FORM 2</div>
   <div *ngSwitchDefault>FORM 3</div>
</div>

If the matches happen to be in a variable, you can use array.indexOf() to avoid the use of the conditional ternary operator.

<div [ngSwitch]="data.type">
  <div *ngSwitchCase="matches[matches.indexOf(data.type)]">FORM 1</div>
  <!-- ... -->
</div>

You can also use the following, which is a lot more flexible. You can then put anything that evaluates to boolean as the *ngSwitchCase value.

<div [ngSwitch]="true">
    <div *ngSwitchCase="data.type === 'multi-choice' || data.type === 'singe-choice'">FORM 1</div>
    <div *ngSwitchCase="data.type === 'range'">FORM 2</div>
    <div *ngSwitchDefault>FORM 3</div>
</div>

The advantage this has over using *ngIf blocks is that you can still specify a default.


You can use ngTemplateOutlet to implement this:

<ng-container [ngSwitch]="variable">
    <ng-container *ngSwitchCase="1">
        <ng-container *ngTemplateOutlet="form1"></ng-container>
    </ng-container>
    <ng-container *ngSwitchCase="2">
        <ng-container *ngTemplateOutlet="form1"></ng-container>
    </ng-container>
    <ng-container *ngSwitchCase="3">FORM 2</ng-container>
    <ng-container *ngSwitchDefault>FORM 3</ng-container>
    <ng-template #form1>FORM 1</ng-template>
</ng-container>

Update

While Angular still considering such feature, there is jonrimmer's switch-cases.directive.ts. Usage example:

<ng-container [ngSwitch]="variable">
    <ng-container *jrSwitchCases="[1, 2]">FORM 1</ng-container>
    <ng-container *ngSwitchCase="3">FORM 2</ng-container>
    <ng-container *ngSwitchDefault>FORM 3</ng-container>
</ng-container>


(Un)fortunately you can‘t; the ngSwitch is quite “dumb” if you look at the source code: it‘s just a === between the case value and the switch value. You have two options, but both of them are far from great.

Option 1 is using the directive *ngSwitchDefault, but this will only work if all your multiple cases are FORM 1:

<div [ngSwitch]="data.type">
  <div *ngSwitchDefault>FORM 1</div>
  <div *ngSwitchCase="'range'">FORM 2</div>
</div>

The other option, which is quite verbose, is doing something like this:

<div [ngSwitch]="data.type">
  <div *ngSwitchCase="data.type === 'multi-choice' || data.type === 'singe-choice' ? data.type : '' ">FORM 1</div>
  <div *ngSwitchCase="'range'">FORM 2</div>
</div>

Tags:

Angular