推到窗体内部的数组时丢失双向绑定

推到窗体内部的数组时丢失双向绑定

本文介绍了推到窗体内部的数组时丢失双向绑定(Angular 2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2构建基本的CRUD应用程序.表单字段之一是一系列配料.我有一个addIngredient方法,该方法将一个新的Ingredient推送到我的ingredients数组中.我单击触发此方法的按钮后,双向绑定似乎丢失了.当查看诊断数据时,一切看起来都正确,但是数据从表单UI中丢失(请参见下面的gif):

I'm building a basic CRUD app with Angular 2. One of the form fields is an array of ingredients. I have an addIngredient method which pushes a new Ingredient to my ingredients array. As soon as I click the button which triggers this method the two-way binding appears to be lost.When looking at the diagnostic data everything appears correct, but the data is lost from the form UI (see gif below):

相关的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之外时,一切都会按预期进行.

NOTE: The div referenced above appears inside a form element. When I move this div outside the form everything works as expected.

推荐答案

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

What is happening here is that the <form> is using input's name properties to synchronise the models' values. In this case it's basically overriding the [ngModel] synchronisation.

您可以通过动态调整name来解决此问题:

What you can do to fix this is make names dynamic:

<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}}" )

(i.e. name="ingredientName_{{i}}")

您可以在文档中详细了解以下内容: https://angular.io/docs/ts/latest/api/forms/index/NgModel-directive.html

You can read more about this in the docs: https://angular.io/docs/ts/latest/api/forms/index/NgModel-directive.html

值得注意的是,在父表单的上下文中,您经常可以跳过单向或双向绑定,因为父表单会为您同步值.

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.

这篇关于推到窗体内部的数组时丢失双向绑定(Angular 2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:04