*angular2 的 ngIf 测试同一属性的三个不同值

*ngIf of angular2 to test on three different values of the same attribute

我是 angular2 的新手,我想使用 *ngIf 但方式有点不同,它不起作用。所以,我在一个对象 item 中有一个属性 type,这种类型只能有 这三个 字符串中的一个:

  1. type_A
  2. type_B
  3. 未指定

并根据 item.type 的值显示图像。我以这种方式使用它,但似乎不起作用(不显示图像):

<li *ngIf="item.type === type_A">
   <img src="assets/images/typeA-icons.png"/>
</li>
<li *ngIf="item.type === type_B">
    <img src="assets/images/typeB-icons.png"/>
</li>
<li *ngIf="item.type === unspecified">
    <img src="assets/images/unspecified-icons.png"/>
</li>

有什么帮助吗?

首先你应该把你的字符串用引号括起来

item.type === 'type_A'

而不是

item.type === type_A

您正在寻找 ngSwitch 运算符https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  <ng-container *ngSwitchCase="match_expression_3">
    <!-- use a ng-container to group multiple root nodes -->
    <inner-element></inner-element>
    <inner-other-element></inner-other-element>
  </ng-container>
  <some-element *ngSwitchDefault>...</some-element>
</container-element>

为什么不用打字稿来做:

public get itemImage() {
  let type = this.item && this.item.type;
  if(type === "type_A") return 'assets/images/typeA-icons.png';
  if(type === "type_B") return 'assets/images/typeB-icons.png';
  return 'assets/images/unspecified-icons.png';
}

HTML

<img [src]="itemImage" />