javascript - 推送到表单内部数组时丢失双向绑定(bind)(Angular 2)

标签 javascript angular

我正在使用 Angular 2 构建一个基本的 CRUD 应用程序。其中一个表单字段是一组成分。我有一个 addIngredient 方法,它将新的 Ingredient 推送到我的 ingredients 数组。只要我单击触发此方法的按钮,双向绑定(bind)就会丢失。 查看诊断数据时,一切看起来都是正确的,但数据从表单 UI 中丢失(请参见下面的 gif):

enter image description here

相关的HTML:

<div *ngFor="let ingredient of newRecipe.ingredients; let i = index; let f = first; let l = last">
  <md-input type="text" id="ingredientName" name="ingredientName" [(ngModel)]="ingredient.name" placeholder="ingredient" required></md-input>
  <md-input type="text" id="ingredientAmount" name="ingredientAmount" [(ngModel)]="ingredient.amount" placeholder="amount" required></md-input>
  <select id="ingredientMeasurement" name="ingredientMeasurement" [(ngModel)]="ingredient.measurement" required>
    <option *ngFor="let measurement of measurements" [value]="measurement">{{measurement}}</option>
  </select>
  <button md-icon-button color="primary" *ngIf="l" (click)="addIngredient()">
    <md-icon>add</md-icon>
  </button>
  <button md-icon-button color="warn" *ngIf="!f" (click)="removeIngredient(i)">
    <md-icon>remove</md-icon>
  </button>
</div>

类中的相关代码:

addIngredient() {
  this.newRecipe.ingredients.push(new Ingredient());
}

注意:上面引用的 div 出现在 form 元素中。当我将此 div 移到 form 之外时,一切都按预期工作。

最佳答案

这里发生的是 <form>正在使用输入的 name属性来同步模型的值。在这种情况下,它基本上覆盖了 [ngModel] 同步。

解决这个问题的方法是 make name动态:

<div *ngFor="let ingredient of newRecipe.ingredients; let i = index;">
   <md-input type="text" name="ingredientName_{{i}}"   
    [(ngModel)]="ingredient.name" placeholder="ingredient" required>
   </md-input>
</div>

(即 name="ingredientName_{{i}}" )

您可以在文档中阅读更多相关信息:https://angular.io/docs/ts/latest/api/forms/index/NgModel-directive.html

When using the ngModel within tags, you'll also need to supply a name attribute so that the control can be registered with the parent form under that name.

It's worth noting that in the context of a parent form, you often can skip one-way or two-way binding because the parent form will sync the value for you.

关于javascript - 推送到表单内部数组时丢失双向绑定(bind)(Angular 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686734/

相关文章:

javascript - 插件编程nodeJs

angular - 在自定义错误处理程序的 Angular2 中,如何使用 .ts 文件中的行号访问错误堆栈跟踪

javascript - onclick 永久更改 html 标题的边框颜色,直到单击另一个标题

javascript - Express Node.js 不工作

javascript - 谁在 JavaScript 中通过嵌套对象进行映射并删除键值对

javascript - Jquery Datepicker onselect调用函数

javascript - 为什么这里需要 'this' 关键字?它指的是什么?

javascript - Angular2 路由器讨厌我的 AUX 路由

angular - ESRI 加载程序搜索小部件聚焦 angular 7 的问题

javascript - document.on click 在页面加载时自动触发