angularswitch-statementcontrol-flowangular-control-flow

Angular 17 @switch multiple values in case


I have angular 17 and i'm using control flow. I want to use @switch

Example:

@switch (variable) {
   @case ("sun")
   {
     //do something
   }
   @case ("sea")
   { 
   }
}

Now i have two different value of variable but do same things, how can i do that? It is possible something like this? :

 @switch (variable) {
   @case ("sun","moon")
   {
     //do something
   }
   @case ("sea")
   { 
   }
}

Solution or suggestions


Solution

  • When you give the switch as true the indivual cases can be rewritten with javascript array method .includes to check for multiple values, this will achieve what you want!

    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [FormsModule],
      template: `
        <input [(ngModel)]="value"/>
        @switch (true) {
          @case (["sun","moon"].includes(this.value))
          {
            <h1>sun or moon</h1>
          }
          @case (this.value === "sea")
          { 
         <h1>sea</h1>
          }
        }
      `,
    })
    export class App {
      value = 'moon';
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo