Reputation: 83
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>
Upvotes: 8
Views: 11607
Reputation: 885
I found another 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 the following condition:
true === !!device.brand
Double exclamation mark, first converts property device.brand
to boolean and then inverts 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)
Upvotes: 9
Reputation: 14395
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>
Upvotes: 10