代码之家  ›  专栏  ›  技术社区  ›  Mathias W

如何在角度嵌套数组中进行双向数据绑定

  •  2
  • Mathias W  · 技术社区  · 7 年前

    假设您有一个任务列表,而任务列表又有一个子任务列表,并且您希望子任务是可更改的-为什么Angular没有正确地双向绑定子任务的数据?

    HTML

    <div *ngFor="let task of tasks">
      Task value: <input [(ngModel)]="task.value">
      <br>
      <div *ngFor="let subtask of task.subtasks">
        Subtask: <input [(ngModel)]="subtask">
        </div>
    </div>
    
    {{ tasks | json }}
    

    TS

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      tasks = [{
        value: 'Task 1',
        subtasks: ['Hello']
      }]  
    }
    

    https://stackblitz.com/edit/angular-agrzfs

    2 回复  |  直到 7 年前
        1
  •  4
  •   Sajeetharan    7 年前

    这里的问题是关于ngfor每个输入必须有一个 unique name . 为了解决这个问题,

    使用 task.subtasks[index] 而不是带有ngmodel的项

    此外,还需要使用trackbyindex以避免速度慢,因为每次更改数组中的字符串时,它都会重新创建DOM。

    <div *ngFor="let subtask of task.subtasks;let index = index;trackBy:trackByIndex;">
        Subtask: <input [(ngModel)]="task.subtasks[index]">
    </div>
    

    STACKBLITZ DEMO

        2
  •  1
  •   Nenad Radak    7 年前

    您需要访问子列表的索引,如此代码段上的索引

    在列表中添加索引计数器并通过tas.sublist访问[i]

       <div *ngFor="let task of tasks">
          Task value: <input [(ngModel)]="task.value">
        <br>
        <div *ngFor="let subtask of task.subtasks; let i = index">
          Subtask: <input [(ngModel)]="task.subtasks[i]">
    
       </div>
     </div>
    
    {{ tasks | json }}
    
    推荐文章