I am building a basic CRUD application with Angular 2. One of the form fields is a set of ingredients. I have an addIngredient
method that pushes the new Ingredient
to my ingredients
array. As soon as I click on the button that launches this method, the two-way binding seems to be lost. When viewing diagnostic data, everything looks correct, but the data is lost from the UI form (see gif below):
Relevant 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>
corresponding code from the class:
addIngredient() { this.newRecipe.ingredients.push(new Ingredient()); }
NOTE. div
mentioned above appears inside the form
element. When I move this div
outside the form
, everything works as expected.
source share