我正在制作一个 Angular2 应用程序,并从服务器检索一系列设备。并非每个设备都具有“品牌”或“类型”属性。我想显示它们中的任何一个,但如果它们都错过了,我想显示“设备#”。 我尝试使用 ngSwitch,但似乎无法使其工作......
<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>
ngSwitch
取实际值:
<div [ngSwitch]="gender">
<div *ngSwitchCase="'male'">...</div>
<div *ngSwitchCase="'female'">...</div>
</div>
您尝试将其用作
ngIf
。
解决您问题的代码是:
<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>
我找到了另一个解决方案。在实现
ngSwitch
时,我们在 ===
参数和 ngSwitch
参数之间有 ngSwitchCase
。我们可以使用它:
<div [ngSwitch]="true">
<a *ngSwitchCase="!!device.brand">{{device.brand}}</a>
<a *ngSwitchCase="!!device.type">{{device.type}}</a>
<a *ngSwitchDefault>Device {{i+1}}</a>
</div>
在幕后我们得到以下条件:
true === !!device.brand
双感叹号,首先将属性
device.brand
转换为布尔值,然后将其反转。例如:
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)