use ngSwitch with on object with conditional attributes in Angular2
Asked Answered
A

2

8

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>
Animate answered 3/11, 2016 at 9:15 Comment(0)
T
9

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>
Tension answered 3/11, 2016 at 9:35 Comment(1)
Thanks, I got solved it eventually with only ngIf the same way you did there.Animate
H
9

I found other solution. In realization of ngSwitch we have === betweeen ngSwitch parameter and ngSwitchCase parameter. We can use it:

<div [ngSwitch]="true">
    <a *ngSwitchCase="!!device.brand">{{device.brand}}</a>
    <a *ngSwitchCase="!!device.type">{{device.type}}</a>
    <a *ngSwitchDefault>Device {{i+1}}</a>
</div>

Under the hood we get follow condition:

true === !!device.brand

Double exclamation mark, first convert property device.brand to boolean and then invert it. For example:

const brand = 'New';
console.log(!brand); // false
console.log(!!brand); // true (exists)

let brand; // undefined
console.log(!brand); // true
console.log(!!brand); // false (not exists)

With best regards!

Hafler answered 23/1, 2019 at 7:44 Comment(4)
!!awesome this should be the answer!Greathouse
Dude, that awesome answer is overlooked. Booum, headshot!Cabrera
This should be considered the correct solution. Worked as a charm! ThanksSplatter
This code could display both brand AND type. So not really a swtich.Gary

© 2022 - 2024 — McMap. All rights reserved.