无法将值绑定到动态垫表的新行中?

我创建了动态垫表,并具有添加新行的按钮。我可以按预期添加新行。但是,如果我在一行中输入值,则相同的值也会反映在其他新行中。我认为[(ngModel)]未正确绑定值。

component.html

  <button mat-raised-button type="button" class="text-upper btnclr" (click)="AddNew()" style='margin-left:10px;color:white;float:left' [disabled]="!AddBillingInfoBtn">
       <mat-icon>add_circle</mat-icon>
   <span> Add New Row</span></button>

  <mat-table [dataSource]="dataSource" class="table" matSort>
         <ng-container *ngFor="let column of displayedColumns" [matColumnDef]="column">
              <mat-header-cell *matHeaderCellDef mat-sort-header>  {{ column }} </mat-header-cell>
                 <mat-cell *matCellDef="let item">
                      <input type="text" autocomplete="off" [(ngModel)]="item[column]">
                 </mat-cell>
         </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
               <mat-row *matRowDef="let row; columns: displayedColumns;" class="element-row" >
          </mat-row>   
   </mat-table>  

component.ts

 this.somedata = {id: "", name: "", amount: ""}
 testArr:any[];
 AddNew(){  
    this.testArr.unshift(this.somedata);
    this.dataSource = new MatTableDataSource(this.testArr);
 }

任何人的帮助将不胜感激!!!

评论
  • cvitae
    cvitae 回复

    You need to create a new object reference for every element you push into the array, otherwise you just keep pushing the same object in there. To create a new reference, you can use the spread operator:

    AddNew(){  
      this.testArr.unshift({ ...this.somedata });
      this.dataSource = new MatTableDataSource(this.testArr);
    }