Angular Material - Triggering Table Data Refresh

12,098

The table doesn't detect dynamic changes at runtime, you have to refresh the table yourself.

Have a look at this example. You can see that after pushing a new element to the array, I have to reset the dataSource manually.

Share:
12,098
Ben Donnelly
Author by

Ben Donnelly

Updated on June 28, 2022

Comments

  • Ben Donnelly
    Ben Donnelly almost 2 years

    I have a angular-material table with the datasource coming from a variable array

    The array can have elements pushed to by the onscreen form. This works fine, and the element is pushed and to ensure it I print out the entire datasource and my the new object is reflected there.

    Here is that code:

    reportFields = [{name: "name_test", filter: "filter_test" }];
     addReportField(){
            this.reportFields.push({
                name: this.fieldToAdd.name,
                filter: this.fieldToAdd.filter
            });
            this.frmField.reset();
            this.changeDetectorRefs.detectChanges();
            console.log(this.reportFields);
        }
    

    reportFields is the datasource, and when the page load the table loads with that data inside. But when I add one during run time, using the addReportField method, the datasource doesn't reload.

    I tried using that ChangeDectectorRef and then detect changes but that didn't work.

    Here is the HTML for the table

    <mat-table [dataSource]="reportFields" style="background: inherit;">
                <ng-container matColumnDef="field">
                    <mat-header-cell *matHeaderCellDef>Field Name</mat-header-cell>
                    <mat-cell *matCellDef="let element">{{element.name}}</mat-cell>
                </ng-container>
    
                <ng-container matColumnDef="filter">
                    <mat-header-cell style="margin-right: 20px;" *matHeaderCellDef>Filter</mat-header-cell>
                    <mat-cell style="margin-right: 20px;" *matCellDef="let element">
                        {{element.filter}}
                    </mat-cell>
                </ng-container>
    
                <ng-container matColumnDef="delete">
                    <mat-header-cell style="text-align: end;" *matHeaderCellDef></mat-header-cell>
                    <mat-cell *matCellDef="let element" style="text-align: end;">
                        <mat-icon (click)="deleteReturn(element.id, 'standard')" style="font-size: 24px; cursor: pointer;" matTooltip="Delete">clear</mat-icon>
                    </mat-cell>
                </ng-container>
    
                <mat-header-row *matHeaderRowDef="reportFieldsColumns"></mat-header-row>
                <mat-row *matRowDef="let row; columns: reportFieldsColumns;"></mat-row>
            </mat-table>
    
  • Gus
    Gus about 4 years
    Link only answer. Pls put the relevant code in the answer itself so that when the link goes dead in the future the answer is still of use.