angularng-switch

use ngSwitch with on object with conditional attributes in Angular2


I am making an Angular2 application and am retrieving an array of devices from the server. Not every device has the attribute 'brand' or 'type'. I want to display either of them, but in case they both miss I want to display 'Device #'. I tried to use an ngSwitch, but can't seem to make it work...

<div *ngFor="let device of devices; let i=index">
  <div [ngSwitch]="device">
    <a *ngSwitchCase="device.brand">{{device.brand}}</a>
    <a *ngSwitchCase="device.type">{{device.type}}</a>
    <a *ngSwitchDefault>Device {{i+1}}</a>
  </div>
</div>

Solution

  • ngSwitch takes actual values:

    <div [ngSwitch]="gender">
      <div *ngSwitchCase="'male'">...</div>
      <div *ngSwitchCase="'female'">...</div>
    </div>
    

    You attempt to use it as ngIf.

    The code that will solve your problem is:

    <div *ngFor="let device of devices; let i=index">
      <div [ngSwitch]="device">
        <a *ngIf="device.brand && !device.type">{{device.brand}}</a>
        <a *ngSwitchCase="device.type && !device.brand">{{device.type}}</a>
        <a *ngIf="!device.type && !device.name">Device {{i+1}}</a>
      </div>
    </div>