Angular2——使用 NgFor 时,每次 keyup 后双向绑定文本输入模糊

Angular2 -- Two-way bound text input blurring after each keyup when using NgFor

所以在 Angular2 应用程序中,我有一个名为 'recipe.ingredients' 的字符串数组,并且我设置了一个表单以允许您编辑成分,并带有添加和删除文本字段(以及数组).

    <ul class="list-unstyled">
      <div class="row" *ngFor="let ingredient of recipe.ingredients; let i=index">
        <li>
          <div class="col-xs-4">
            <input
              size="20"
              type="text"
              class="form-control"
              [ngModel]="recipe.ingredients[i]"
              #t
              (blur)="recipe.ingredients[i]=t.value"
              required>
          </div>
          <div class="btn-group col-xs-2" role="group">
            <button
              type="button"
              class="btn btn-default btn-xs"
              (click)="recipe.ingredients.splice(i,1)">-</button>
            <button
              type="button"
              class="btn btn-default btn-xs"
              (click)="recipe.ingredients.splice(i+1,0,'')">+</button>
          </div>
        </li>
      </div>
    </ul>

你会注意到我没有用 [(ngModel)] 对 recipe.ingredients[i] 进行双向绑定,那是因为我试过了,每次你输入一个字符时,文本盒子会失去焦点。我假设它与 *ngFor 跨过数组有关。不管怎样,暂时这个解决方法很好,但现在我要添加一些功能,我需要两种方式的数据绑定才能工作。知道如何重构它以使其正常工作吗?

使用trackBy:

<div class="row" *ngFor="let ingredient of recipe.ingredients; let i=index; 
 trackBy:customTrackBy">
  [(ngModel)]="recipe.ingredients[i]"
customTrackBy(index: number, obj: any): any {
  return index;
}

归功于 Günter:, which can be found with this SO search: https://whosebug.com/search?q=%5Bangular2%5D+ngfor+ngmodel


解决此处所示问题的另一种方法 是使用对象数组而不是基元数组。所以而不是

recipe = { ingredients: ['salt', 'flour'] };

使用

recipe = { ingredients: [{item: 'salt'}, {item: 'flour'}] };