【问题标题】:Angular2 -- Two-way bound text input blurring after each keyup when using NgFor [duplicate]Angular2——使用NgFor时,每次按键后双向绑定文本输入模糊[重复]
【发布时间】:2016-10-19 15:20:03
【问题描述】:

因此,在 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 跨过数组有关。无论如何,目前这种解决方法很好,但现在我正在添加一些功能,我需要两种方式的数据绑定才能工作。知道如何重构它以使其正常工作吗?

【问题讨论】:

    标签: javascript typescript angular angular2-forms


    【解决方案1】:

    使用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:https://stackoverflow.com/a/36470355/215945,可通过此 SO 搜索找到:https://stackoverflow.com/search?q=%5Bangular2%5D+ngfor+ngmodel


    https://stackoverflow.com/a/33365992/215945 所示,解决问题的另一种方法是使用对象数组而不是基元数组。所以不是

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

    使用

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

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2017-01-13
      相关资源
      最近更新 更多