How to add data dynamically to mat-table dataSource? How to add data dynamically to mat-table dataSource? angular angular

How to add data dynamically to mat-table dataSource?


I have found a solution for this problem, basically if you do:

this.dataSource.data.push(newElement); //Doesn't work

But if you replace the complete array then it works fine. So your final code must be :

this.socket.on('newMessage', function(event) {    const data = this.dataSource.data;    data.push(event);    this.dataSource.data = data;});

You can see the issue here -> https://github.com/angular/material2/issues/8381


The following solution worked for me:

this.socket.on('newMessage', function(event) {    this.dataSource.data.push(event);    this.dataSource.data = this.dataSource.data.slice();});

Another solution would be calling the _updateChangeSubscription() method for the MatTableDataSource object:

this.socket.on('newMessage', function(event) {    this.dataSource.data.push(event);    this.dataSource._updateChangeSubscription();});

This method:

/** Subscribe to changes that should trigger an update to the table's rendered rows. When the changes occur, process the current state of the filter, sort, and pagination along with the provided base data and send it to the table for rendering. */


Here is a very simple and easy solution:

displayedColumns = ['ticketNum', 'assetID', 'severity', 'riskIndex', 'riskValue', 'ticketOpened', 'lastModifiedDate', 'eventType'];dataSource: any[] = [];constructor() { }ngOnInit() {}onAdd() {  //If you want to add a new row in the dataSource   let model = { 'ticketNum': 1, 'assetID': 2, 'severity': 3, 'riskIndex': 4, 'riskValue': 5, 'ticketOpened': true, 'lastModifiedDate': "2018-12-10", 'eventType': 'Add' };  //get the model from the form   this.dataSource.push(model);  //add the new model object to the dataSource   this.dataSource = [...this.dataSource];  //refresh the dataSource}

Hope this will help :)