I have an Angular Material Data Table that I created using ng generate @angular/material:material-table --name=BHTable.
I am trying to test how to dynamically change the contents of the table at runtime. In order to do this I want to create a button that clears the table by setting the datasource array to empty.
In my datasource.ts I have a function I added to change the datasource of the table.
public UpdateData(IncomingData: BhTableItem[]){
this.data = IncomingData;
}
When I press the button I made it calls a function in my normal (not datasource) components.ts which has this code.
public UpdateTest(){
this.dataSource.UpdateData([]);
}
This should update the dataSource in the table, and change the contents of the table. However, when I press the button nothing happens.... I have read many different posts trying to figure this out but I have not gotten it to work. I think the answer has something to do with my method not firing the observable to update the table, but I am not sure. Any help would be greatly appreciated!
Edit: I forgot to mention. When I put my line into ngOnInit it looks like it works to change the contents of the table on page load. I want this same functionality, but for it to happen when I press the button.
ngOnInit() {
this.dataSource = new BhTableDataSource();
this.dataSource.UpdateData([]);
}
HTML since it was asked for.
<div class="mat-elevation-z8">
<table mat-table class="full-width-table" matSort aria-label="Elements">
<!-- Id Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
<td mat-cell *matCellDef="let row">{{row.id}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{row.name}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator
[length]="dataSource?.data.length"
[pageIndex]="0"
[pageSize]="50"
[pageSizeOptions]="[25, 50, 100, 250]">
</mat-paginator>
</div>
<button (click)="UpdateTest()"> Clear Table </button>