2017-10-07 49 views
1

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

这是我的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", 
    ] 
} 

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

+0

你不能像这样绑定表格单元到'ngModel'。你必须以不同的方式做。 – asmmahmud

回答

0

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

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

当我使用 的表被加载,但没有内容,当我改变表内的值它不会改变我的数组 –