0

I'm implementing a material table in Angular and I'm struggling to make it dynamic. So far I'm able to add columns dynamically, but trying to do the same with rows just doesn't work.

the addColumn() function adds a column dynamically without having to refresh anything.

addColumn() {
   this.columns.push(this.formInput.value);
}

Trying to do the same with row doesn't make any change without essentially 'refreshing' the table, i.e. hiding it and then re-showing it using a toggle.

addRow() {
   this.rowsData.push(this.otherFormInput.value);
}
<mat-table [dataSource]="rowsData">
   <ng-container *ngFor="let column of columns" [matColumnDef]="column">
      <mat-header-cell *matHeaderCellDef> {{ column }} </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{ element[column] }} </mat-cell>
   </ng-container>

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

Is there any way around this? Any help would be greatly appreciated.

SkinnyBetas
  • 461
  • 1
  • 5
  • 27

2 Answers2

1

Your variable rowsData is the table's dataSource, so if you are pushing the data into this dataSource it will not work.

You should do something like this:

addRow() {
   this.rowsData.data.push(this.otherFormInput.value);
}
Tushar
  • 1,948
  • 1
  • 13
  • 32
1

I want to add one more line with Tushar's answer.

You should do something like this:

addRow() {
   this.rowsData.data.push(this.otherFormInput.value);
   // add this line also.
   this.dataSource.filter = "";
}
Vikas Gupta
  • 1,183
  • 1
  • 10
  • 25