我有一个像这样生成的表单:
<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)
答案 0 :(得分:0)
您必须跟踪数组项。否则整个ngFor都会被重新渲染。这就是你失去输入值的原因。
试试:
<div *ngFor="let item of dag1; let i = index; trackBy: trackByFn">
并实现以下功能:
trackByFn(index, item) {
return index;
}
答案 1 :(得分:0)
还更改每个name
元素的input
属性值:
<input name="hoeveelheid{{i}}" ...>