0

I have implement table using MatTableModule in angular using typescripts.

It is working fine when I assign value to datasource like this,

let dataRow = {name: dealerInfo.name, address: dealerInfo.address, town: dealerInfo.town, contact:dealerInfo.contact};
this.dataSource = [dataRow];

As I need to add rows dynamically I used push() as follows (but it doesn't work, it does not show data in the html),

let dataRow = {name: dealerInfo.name, address: dealerInfo.address, town: dealerInfo.town, contact:dealerInfo.contact};
this.dataSource.push(dataRow);

This is how my data source defined.

dataSource: any [] = [];

What should be the correct way of adding elements dynamically?

2
  • This is like saying "push elements to array does not work in Javascript". There's no such thing as Typescript as far as the browser is concerned. Can you recreate your problem in a Stackblitz? Commented May 3, 2020 at 8:37
  • 1
    Does this.dataSource = [...this.dataSource, dataRow]; work? In that case it's Angular's change detector that doesn't pick up the call to push. Commented May 3, 2020 at 8:39

2 Answers 2

3

The correct way to create a MatTableDatasource is to create an instance of it that you pass as [dataSource] property

dataSource: MatTableDataSource<any> = new MatTableDataSource<any>();

You can pass initial data in the constructor. Then you push to its data property

this.dataSource.data.push(dealerInfo);

Since you are copying properties 1:1 by name, there's no need to create intermediate objects first.

Also, create an interface instead of using any

export interface TableRow {
    name: string;
    ...
}

and

new MatTableDataSource<TableRow>();

Documentation:

DataSource

For most real-world applications, providing the table a DataSource instance will be the best way to manage data. The DataSource is meant to serve a place to encapsulate any sorting, filtering, pagination, and data retrieval logic specific to the application.

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

2 Comments

this.dataSource.data.push(dealerInfo); did not work. Instead I have defined another array of TableRow type and collect all the rows to it. Finally assign it to this.dataSource.data and it works.
That's not how it should be done. Very ineffective. @abo
0

With the support of @baao's answer I solved the issue as follows,

  // Defined variables.
  rowDataArr: RowData[] = [];
  dataSource: MatTableDataSource<RowData> = new MatTableDataSource<RowData>();

And once I received data from back end.

valuesFromBackEnd.forEach(rowData=> {
          this.rowDataArr.push(rowData);
        });
        this.dataSource.data = this.rowDataArr;

Comments

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.