Search code examples
javascriptangulartypescriptweb-frontendangular-material-table

How would I be able to dynamically update an angular table using material table?


Currently, what I have is this.

export class TableComponent<T> implements OnInit {

    displayedColumns: Array<string> = [];
    dataSource: MatTableDataSource<T> = new MatTableDataSource();

    constructor(public asmErrorServ: AssemblyErrorService) { }

    ngOnInit(): void {
        this.displayedColumns = ['Message Type', 'Message', 'Message Date'];
        this.dataSource = (<any>this.asmErrorServ).asmErrorLog;
    }
}

The this.datasource gets updated from the asmErrorServ which has an array that stores errors or warnings real-time. That part of the code appears like this in the errorservice.

export class AssemblyErrorService{
...

error(message: string): void {
        let newError: asmMessage = { type: 'error', message: message, time: Date.now() };
        this.asmErrorLog.push(newError);

        this._snackBar.open(this.generateSnackbarString(newError), 'Dismiss', {
            duration: 3000,
            horizontalPosition: this.horizontalPosition,
            verticalPosition: this.verticalPosition,
            panelClass: ['red-snackbar', 'login-snackbar'],
        });
    }
}

The out looks like this and the table does not seem to get updated real-time. I was wondering on how to fix it if there's a way to do it?


Solution

  • You have to re-initialize the data source property, like below:

    this.asmErrorLog.push(newError);
    this.dataSource.data = this.asmErrorLog;
    

    Now the table will be updated in real time.