Angular 4 表单输入正在重置

Angular 4 form input is being reset

我有一个正在生成的表单:

<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>

当我添加另一行输入时:

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

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

显示了新的输入字段,但之前的输入字段行被清空,但该行的值仍然设置为这样(考虑到我添加了 hoeveelheid = 50 和 voedingtijd= 12:30):

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

为什么我的输入字段被清空,而值仍然设置?

编辑:

newSegment() 代码(只是创建一个空模型实例):

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

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)

您必须跟踪您的阵列项目。否则整个 ngFor 被重新渲染。这就是您丢失输入值的原因。

试试看:

<div *ngFor="let item of dag1; let i = index; trackBy: trackByFn">

并实现如下功能:

trackByFn(index, item) {
  return index;
}

还更改 name 每个 input 元素的属性值:

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