1

With simple form or array items:

      <div *ngFor="let ingredient of recipe.ingredients; let i = index">
        <div>
          <input type="text" [name]="i + '_ingName'" [(ngModel)]="ingredient.name" required>
        </div>
        <div>
          <button type="button" (click)="removeIngredient(i)">X</button>
        </div>
      </div>
      <button type="button" (click)="addIngredient()">Add Ingredient</button>

And button methods:

addIngredient() {
  this.recipe.ingredients.push(new Ingredient('New ingredient...', 0));
  console.log(this.recipe.ingredients);
}

removeIngredient(i: number) {
  this.recipe.ingredients.splice(i, 1);
  console.log(this.recipe.ingredients);
}

And initial values:

First Ingredient, Second Ingredient

Then remove first:

Second Ingredient

Then add new:

New Ingredient, New Ingredient

When removed first ingredient, everything is working fine - form is left with Second Ingredient. But then, when adding new ingredient, both resulting items are "New ingredient", even with correct array log on console after adding: "Second Ingredient" and "New Ingredient". Why did the Second Ingredient disappear on the form?

However, when the second element is spliced firstly, everything looks fine even after adding new child item....

Stackblitz: https://stackblitz.com/edit/angular-rw7a5h

MGorgon
  • 2,547
  • 23
  • 41