Angular 2+将表格单元格绑定到数组记录

时间:2017-10-07 11:51:52

标签: javascript html angular

我有一个从json生成的表。 每个单元格都是可编辑的。 我想将每个单元格绑定到每个数组记录。 我需要这个,因为我想让用户更改每个单元格,然后让他将其保存在服务器上。

这是我的HTML

<table class="table table-bordered table-hover table-striped" *ngIf="lifeSphere">

  <tr>
    <th *ngFor="let date of lifeSphere.lifeSphereDates" [(ngModel)]="date">{{date}}</th>
  </tr>

  <tr *ngFor="let row of lifeSphere.lifeSphereRows">
    <td *ngFor="let cell of row.lifeSphereCell" contenteditable>{{cell}}</td>
  </tr>

</table>


<button (click)="saveLifeSphere()" class="btn btn-success">Save</button>

错误讯息:

Cannot assign to a reference or variable!

Json示例

{
  "id": 10,
  "lifeSphereRows": [
    {
      "id": 1,
      "lifeSphereCell": [
        "0/0",
        "0/1",
        "0/2",
      ]
    },
    {
      "id": 2,
      "lifeSphereCell": [
        "1/0",
        "1/1",
        "1/2",
      ]
    },
    {
      "id": 3,
      "lifeSphereCell": [
        "2/0",
        "2/1",
        "2/2",
      ]
    },
  ],
  "lifeSphereDates": [
    "2017-10-05T22:31:41.539",
    "2017-10-05T22:31:41.541",
    "2017-10-05T22:31:41.541",
  ]
}

我认为最好的解决方案是使用双向数据绑定,但是可以在这里使用吗?

1 个答案:

答案 0 :(得分:0)

您只能将组件的属性(字段)分配给 ngModel 。试试这个,

<tr>
    <th *ngFor="let date of lifeSphere.lifeSphereDates" [(ngModel)]="lifeSphere.lifeSphereDates[i]">{{date}}</th>
</tr>