我要在单击按钮时添加一个材料扩展面板,然后尝试将内容的值绑定到模型数组的每个索引中。我的数组中定义了另一个数组,这在分配嵌套数组的值时让我头疼。第一个索引正确绑定,但是数组的第二个和第三个索引重复。我也在做2种方式的绑定,将其删除并将其绑定到服务。
第一个索引正确绑定,但数组的第二个和第三个索引重复。我也在做2种方式的绑定,将其删除并将其绑定到服务。
<mat-card>
<mat-card-content>
<div class="pesticide-info">
<h2 class="h3 text-center">Pesticide Information</h2>
<mat-accordion>
<mat-expansion-panel *ngFor="let item of recordPesticideInfos; let i = index" [attr.data-index]="i">
<mat-expansion-panel-header>
<mat-panel-title>
Pesticide Product
</mat-panel-title>
<mat-panel-description>
Enter the Pesticide Information
</mat-panel-description>
</mat-expansion-panel-header>
<div *ngFor="let pest of item.pesticideInfo; let j = index" [attr.data-index]="j">
<mat-form-field [floatLabel]="auto">
<mat-label>Product</mat-label>
<!-- <input name=Product{{index}} [(ngModel)]="recordPesticideInfos[index].pesticideInfo[index].Product" placeholder="item">-->
<input matInput placeholder="Product Name" [(ngModel)]="pest.Product" name=Product{{countOfProduct}}
#Product="ngModel">
</mat-form-field>
</div>
</mat-expansion-panel>
<div class="add-product text-center">
<a class="btn btn-success text-white" (click)="addItem()" style="text-align: center"><i
class="fa fa-plus"></i> Add Product</a>
</div>
</mat-accordion>
</div>
</mat-card-content>
export class RecordPesticideInfo {
RecordPesticideInfosId: number;
RecordId: number;
PesticideInfoId: number;
CountOfPestcideProduct: number;
title: string;
description: string;
pesticideInfo: PesticideInfo[];
}
addItem() {
// push object that you need to be added into array
this.recordPesticideInfos.push({
RecordPesticideInfosId: null, RecordId: null,
PesticideInfoId: null, CountOfPestcideProduct: this.countOfProduct++,
title: "Pesticide Product", description: "Enter the Pesticide Information",
pesticideInfo: this.pesticides as PesticideInfo[]
// pesticideInfo: Object.keys(this.pesticides).map(i => this.pesticides[this.countOfProduct++])
});
}
我想在每次单击按钮时绑定一个新的array值 这是stackblitz网址:https://stackblitz.com/edit/angular-ylqkum
答案 0 :(得分:0)
问题出在这一行:
pesticideInfo: this.pesticides as PesticideInfo[]
每次添加新产品时,都会从this.pesticide成员变量中获得完全相同的对象引用。
它对第一个项目起作用的原因是在那里您内联创建了新对象:
pesticideInfo: [{
PesticideInfoId: null,
Product: null
}]
我为创建新的默认产品项添加了此新功能:
private createNewPesticide() {
return {
PesticideInfoId: null,
Product: null
}
}
检查工作的webview 75。