将 Form HTML 标签与 ngFor 一起使用会导致 ngModel 使用循环变量的最新结果而不是当前结果

Using the Form HTML tag with ngFor causes the ngModel to use the latest result of the looping variable instead of the current one

请看下面的Plnkr。如果您取消注释 app.html 中的 html 标签,所有孩子都将是 Tim。

<!--<form #form="ngForm">-->
  <div class="row">
    <div class="col-lg-12" *ngFor="let employee of employees">
      <div class="col-lg-6">
        <label for="employee">Employee</label>
        <input type="text" class="form-control" id="employee" [(ngModel)]="employee.firstName" name="employee">
      </div>
      <div class="row">
        <div class="col-lg-12" *ngFor="let kid of employee.kids" style="border:1px solid #cecece;">

          <div class="col-lg-4">
            <label for="kid">Kid - {{kid.name}}</label>
            <input type="text" class="form-control" id="kid"  [(ngModel)]="kid.name" name="kid">
          </div>

        </div>


      </div>
    </div>
  </div>
<!--</form>-->

https://plnkr.co/edit/AyOVBXAoa8kuE1CQf6XB?p=preview

我想使用 Angular2 表单功能,因此不能跳过它并用一些 javascript 替换它。

[ngModelOptions]="{ standalone : true }" 添加到 for 循环的输入中,使它们都是唯一的(更准确地说,它们不会被添加到相同的 FormGroup 实例):

<input type="text" class="form-control" id="kid"  [(ngModel)]="kid.name" 
[ngModelOptions]="{ standalone : true }" name="kid">