angularng-switchangularjs-ng-switch

Can you pass an array of values into an ngSwitch?


I have a functioning ngSwitch

<div class="columnFormatting" [ngSwitch]="statusIds">
  <div *ngSwitchCase="2"> Do 2 </div>
  <div *ngSwitchCase="4"> Do 4 </div>
  <div *ngSwitchDefault> Default </div>
</div>

StatusIds can contain one or more integers separated by commas.

If statusIds is [2,4] I want it to hit both cases. Is this possible without a foreach loop outside of the switch?


Solution

  • ngSwitch only takes single value,but in order to display multiple cases you can do the following.

    <div class="columnFormatting" *ngFor="let status of statusIds" [ngSwitch]="status">
      <div *ngSwitchCase="2"> Do 2 </div>
      <div *ngSwitchCase="3"> Do 4 </div>
      <div *ngSwitchDefault> Default </div>
    </div>
    

    With the combination of ngFor and ngSwitch you can achieve what you asked. You don't need to have a for loop outside the switch,you can have along with switch as I mentioned above.

    For further reference

    I hope this will help you. If you have any problems or suggestions let me know.