I am using Angular Material Mat-Table. how to change this data into a mat-table data source format. can someone help me to change this data as mat-table dataSource?
https://stackblitz.com/angular/jnmrolgdbaj?file=src%2Fapp%2Ftable-basic-example.ts
"timelineitems": [
{
"1/29/2020": {
"new_daily_cases": 0,
"new_daily_deaths": 0,
"total_cases": 0,
"total_recoveries": 0,
"total_deaths": 0
},
"1/30/2020": {
"new_daily_cases": 1,
"new_daily_deaths": 0,
"total_cases": 1,
"total_recoveries": 0,
"total_deaths": 0
},
"1/31/2020": {
"new_daily_cases": 1,
"new_daily_deaths": 0,
"total_cases": 1,
"total_recoveries": 0,
"total_deaths": 0
}
}
]
Here is the way you can merge the array given by you into a iterable Array .
const TIMELINE_ITEMS = [ { "1/29/2020": { "new_daily_cases": 0, "new_daily_deaths": 0, "total_cases": 0, "total_recoveries": 0, "total_deaths": 0 }, "1/30/2020": { "new_daily_cases": 1, "new_daily_deaths": 0, "total_cases": 1, "total_recoveries": 0, "total_deaths": 0 }, "1/31/2020": { "new_daily_cases": 1, "new_daily_deaths": 0, "total_cases": 1, "total_recoveries": 0, "total_deaths": 0 } } ]; let finalArray = []; let data = TIMELINE_ITEMS[0]; Object.keys(data).forEach((key)=>{ let obj = { date : key, ...data[key] } finalArray.push(obj); }); console.log(finalArray);
Once you have the flat array, set the table columns
and datasource
as below :
this.displayedColumns = Object.keys(finalArray[0]);
this.dataSource = finalArray;
Here is the working stackblitz demo : Stackblitz Demo
If you use as data
data=TIMELINE_ITEMS[0]
You can use as source data|keyvalue
<table mat-table [dataSource]="data|keyvalue" class="mat-elevation-z8">
And yours columns
{{element.key}}
{{element.value.new_daily_cases}}
{{element.value.new_daily_deaths}}
...
In this case, which Displayed columns we can use?. Well, you can has a fake displayed columns
displayedColumns:string[]=["1","2","3","4","5","6"]
if we use the columns as show it above
See stackblitz
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.