Search code examples
angularangular-formsngmodel

Angular 4 form input is being reset


I have a form that is being generated like so:

<div *ngFor="let item of dag1; let i = index">
      <mat-form-field>
        <input matInput placeholder="Product..." [value]="dag1[i].product.productName" [matAutocomplete]="product" [formControl]="productControl">
        <mat-autocomplete #product="matAutocomplete">
                <mat-option *ngFor="let product of options" (click)="editInput(product, i)">
                    {{ product.productName }}
                </mat-option>
            </mat-autocomplete>
      </mat-form-field>
      <mat-form-field>
            <input matInput placeholder="Hoeveelheid..." name="hoeveelheid" [(ngModel)]="dag1[i].hoeveelheid" required>
      </mat-form-field>
      <mat-form-field>
            <input matInput placeholder="Tijd..." name="voeding_tijd" [(ngModel)]="dag1[i].voeding_tijd" required>
      </mat-form-field>
      <span (click)="removeDag1(item)"><i class="material-icons">clear</i></span>
    </div>
<span (click)="addDag1()"><i class="material-icons">add</i></span>

When I add another row of inputs with:

 <span (click)="addDag1(1)"><i class="material-icons">add</i></span>

 // Component
 addDag1(){
    this.dag1.push(this.newSegment());
 }

The new input fields are displayed but the former input field row is being emptied, but the values of that row are still set like so (considering I added hoeveelheid = 50 and voedingtijd= 12:30):

"voeding_tijd": "12:30",
"hoeveelheid": "50"

Why are my input fields being emptied while the values are still set?

EDIT:

newSegment() code (just creates an empty model instance):

 newSegment() : Voedingssegment{
     let voedingssegment = new Voedingssegment();
     voedingssegment.product = new Product();
     return voedingssegment;
 }

Model used with dag1 :

    constructor(
    public id?: number,
    public productcode?: number,
    public product?: Product,
    public voeding_tijd?: string,
    public voeding_dag?: string,
    public voedingschema_id?: number,
    public hoeveelheid?: number)

Solution

  • Change also name attribute value of each input element:

    <input name="hoeveelheid{{i}}" ...>