*ngIf 中字符串动态变量的变量字段名称/属性名称

Variable field name / attribute name from string dynamic variable in *ngIf

在我正在开发的 angular 5 应用程序中,我从 dynamodDB 检索了一个看起来像这样的 json(它作为数组检索并与 [=13 一起使用=], 但为了简单起见,我可以说它是这样存储在组件中的":

public person = {
  "userID" : "abc123...",
  ...
  "period1_status" : "applied",
  "period2_status" : "placed",
  "period3_status" : "applied",
  ...
}

在我的组件中,我有一个名为 chosenPeriod 的变量字符串,我可以使用 <select> 标记对其进行更改。它更改为 'period1''period2''period3'

public chosenPeriod = 'period2'

在组件的 html 的其他部分,我有一个 <mat-chip>(使用 material2),如果 periodX_status 等于 'applied',我只想显示它,其中 X 是 chosenPeriod 的值。像这样的东西:

<mat-chip *ngIf="person.chosenPeriod+'_status' == 'applied'"><mat-icon>drag_handle</mat-icon></mat-chip>

我想要它的位置 *ngIf="person.period1_status == 'applied' 如果 chosenPeriod = 'period1' 等等

上面的例子当然不行。但是 angular5 / HTML 有办法做到这一点吗?

可以使用object property accessors/bracket notation,如下:

<mat-chip *ngIf="person[chosenPeriod + '_status'] == 'applied'">

在上面的示例中,如果 chosenPeriod'period1',则与:

相同
<mat-chip *ngIf="person['period1' + '_status'] == 'applied'">

与以下相同:

<mat-chip *ngIf="person['period1_status'] == 'applied'">

最后,效果相同的是:

<mat-chip *ngIf="person.period1_status == 'applied'">