【问题标题】:Variable field name / attribute name from string dynamic variable in *ngIf*ngIf 中字符串动态变量的变量字段名/属性名
【发布时间】:2018-04-01 23:52:28
【问题描述】:

在我正在开发的 angular 5 应用程序中,我从 dynamodDB 检索了一个看起来像这样的 json(它作为数组检索并与 *ngFor 一起使用,但为了简化这个问题,我可以说它是这样存储在组件中的”:

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

在我的组件中,我有一个名为 selectedPeriod 的变量字符串,我可以使用 <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>

如果chosenPeriod = 'period1' 等,我希望它在*ngIf="person.period1_status == 'applied' 的位置。

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

【问题讨论】:

    标签: angular angular-ng-if


    【解决方案1】:

    你可以使用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'">
    

    【讨论】:

    • 如果它引起了“哇”,除了标记为例外之外,我还建议您投票。
    • @Engam 啊,我明白了。
    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2021-03-07
    • 2018-02-14
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多