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