【问题标题】:How to access key and value of object (with reference) using *ngFor?如何使用 *ngFor 访问对象的键和值(有参考)?
【发布时间】:2018-07-30 15:14:24
【问题描述】:

我遇到了一个严重的问题how to get Key and Value of JSON object using *ngFor,并找到了一个很好的解决方案here(以防这个问题被标记为重复)

我使用了Pipes,但是solution 似乎效率很低,因为它每次更改检测器检查更改时都会生成集合。忽略复杂性并使用此解决方案,仍然没有解决问题,因为它迭代了从组件返回的新数组。

如何使用此解决方案来操作原始对象?

业务需求:保持 Key/Value 对不受限制,并允许用户在 both 上更改它们前端。

下面是sn-p的代码:

<tr *ngFor="let properties of matrixProperties">
    <button (click)="addNewProperty(properties)">Add New Property</button>
    <div *ngFor="let property of properties | keys">
        <td>
            <inline-editor type="textarea" [(ngModel)]="property.key"></inline-editor>
        </td>
        <td>
            <inline-editor type="textarea" [(ngModel)]="property.value"></inline-editor>
        </td>
    </div>
</tr>

addNewProperty(properties) {
  properties.id = 4;
  properties['key'] = "value";   //adding new key/value pair
}

【问题讨论】:

    标签: angular typescript pass-by-reference


    【解决方案1】:

    &lt;div *ngFor="let property of properties | keys"&gt; 在属性中,您将获得对象数组。

    for (const prop in this.properties) {
              if (this.properties.hasOwnProperty(prop)) {
                this.ResultData.push(prop);
              }
            }
    

    在 ResultData 数组中,只有键存在将 ResultData 映射到 ngFor,您将只获得键

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 2020-10-23
      相关资源
      最近更新 更多