1

我有一个正在生成的表单,如下所示:

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

2 回答 2

0

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

试试看:

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

并实现如下功能:

trackByFn(index, item) {
  return index;
}
于 2018-01-15T16:29:28.930 回答
0

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

<input name="hoeveelheid{{i}}" ...>
于 2018-01-15T17:41:08.923 回答