在 Angular2 中将 ngSwitch 与具有条件属性的对象一起使用

use ngSwitch with on object with conditional attributes in Angular2

我正在制作一个 Angular2 应用程序并从服务器检索一组设备。并非每个设备都具有 'brand' 或 'type' 属性。我想显示它们中的任何一个,但如果它们都错过了,我想显示 'Device #'。 我尝试使用 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转成boolean再取反。例如:

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)

谨致问候!