3

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>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.