Reputation: 364
I have created dynamic mat table and having button to add the new row. I can able to add the new row as expected. But, If i enter the value in one row, the same value reflecting in other new rows as well. I think [(ngModel)] is not binding the values properly.
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);
}
Anyone help will be Appreciated!!!
Upvotes: 1
Views: 449
Reputation: 71971
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);
}
Upvotes: 2