首页 > 解决方案 > 如何将特定索引的数组分配给另一个嵌套数组?

问题描述

我在单击按钮时添加了一个材质扩展面板,并尝试将内容的值绑定到模型数组的每个索引中。我的数组中定义了另一个数组,这让我在分配嵌套数组的值时很头疼。第一个索引正确绑定,但数组的第二个和第三个索引重复。我也在做 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++])
});  

}

我想在每个按钮上绑定一个新的数组值单击这是 stackblitz url:https ://stackblitz.com/edit/angular-ylqkum

标签: javascripthtmlarraysangularangular8

解决方案


问题出在这一行:

pesticideInfo: this.pesticides as PesticideInfo[]

每次添加新产品时,它都会从 this.pesticide 成员变量中获得完全相同的对象引用。

它适用于第一项的原因是您在内联创建了新对象:

pesticideInfo: [{
    PesticideInfoId: null,
    Product: null      
}]

我为创建新的默认产品项目添加了这个新功能:

  private createNewPesticide() {
    return {
      PesticideInfoId: null, 
      Product: null
    }
  }

检查工作的stackblitz


推荐阅读