Losing two-way binding when pushing to array inside form (Angular 2)

前端 未结 1 1246
清歌不尽
清歌不尽 2020-12-30 04:10

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 Ingred

相关标签:
1条回答
  • 2020-12-30 04:33

    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.

    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>
    

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

    You can read more about this in the docs: 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.

    0 讨论(0)
提交回复
热议问题