首页 文章

将ngModel绑定到带有输入行的网格中的第二级ngFor,Angular 2

提问于
浏览
1

我需要帮助,我一直在尝试用几天来创建一个带有对象的网格,然后插入到一个数组中 . 网格中的每一行代表具有选择下拉列表的对象和带有输入框的colomns列表 . 我的问题是,当我更改表示我的输入框的headItem值时,该值将通过( onRowClick() )保存到数组中的所有对象 . 我想知道我是否可以在一行上设置ngModel来仅更新该行的值 .

注意:DOM对象显示正确,因为我索引了headItem值 headItem.value[childIndex]

<tr *ngFor='#row of listRows; #parentIndex = index'>
        <td>
            <select
                [(ngModel)]="color[parentIndex]"
                (ngModelChange)="sendColorEvent($event, row)"
                class="form-control">
                <option *ngFor='#obj of row.availableColors'>{{obj}}</option>
            </select>
        </td>
        <td *ngFor='#headItem of row.headList; #childIndex = index'>
          <input [(ngModel)]="headItem.value[childIndex]" (ngModelChange)="onRowClick($event, row, headItem)" type="number">
        <td>
          <input readonly="readonly" [(ngModel)]="totalAmount" type="number">
        </td>
    </tr>

在控制台日志中,您可以看到在数组中,所有行都具有相同的值,最后一个键入 .

onRowClick(quantity, row, headItem) {
  headItem.value = quantity;
  console.log(this.listRows)
  this.getTotal();
 }

enter image description here

PLunker grid

1 回答

  • 1

    您面临的问题是,在您的代码中,当您创建对象的两个实例时:

    const gblRowVal1 = 
         new GridRowValues(1, this.color, this.headList, this.availableColors)
    
    const gblRowVal2 = 
         new GridRowValues(2, this.color, this.headList, this.availableColors)
    

    您正在设置相同的数组 headList (和 availableColors ,您使用的是不同的,因此数组相同并不重要) .

    使用相同的数组意味着数组当然对两个对象都是相同的 . 所以无论你对一个阵列做什么,都会发生在另一个阵列上 .

    你需要做的是深度克隆该数组 . 浅拷贝不起作用,因为它仍然保留对象引用,我们也需要摆脱它 . 对于深度克隆,存在一些可能的解决方案,例如使用 lodash 库 . 但是我们也可以通过将现有数组映射到新数组并使用 Object.assign 来实现:

    const gblRowVal1 = new GridRowValues(1, this.color, 
       this.headList.map(x => Object.assign(new RefQuantities(), x )),
       this.availableColors)
    
    const gblRowVal2 = new GridRowValues(2, this.color, 
       this.headList.map(x => Object.assign(new RefQuantities(), x )), 
       this.availableColors)
    

    如果你想查看它们,还有其他解决方案:How do you clone an Array of Objects in Javascript?我个人喜欢我向你展示的上述方法,特别是因为你想将数据转换为你的类 RefQuantities .

    现在这些数组是不同的数组,其中任何一个中的更改都不会影响另一个 .

    这是你的傻瓜:https://plnkr.co/edit/HozFyjGvwL6mgmclliiW?p=preview

相关问题