[英]How to two-way data bind in nested array in 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']
}]
}
这里的问题是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>
您需要像此代码片段一样访问子列表的索引
在列表上添加索引计数器,并通过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 }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.