I have a nested array and I want to display this with mat-table.
In the array are two different modules "Flex" with several positions that are to be displayed in a table.
Since there are two "Flex" modules in the array, two tables should also be displayed like this example:
FLEX
Position | ID | Menge | Bezeichnung | BP_Gesamt |
---|---|---|---|---|
1 | STZBH | 2 | Xpress weiss | 1998,00 |
2 | STZBG | 5 | Xpress schwarz | 3998,00 |
FLEX
Position | ID | Menge | Bezeichnung | BP_Gesamt |
---|---|---|---|---|
1 | STZBH | 4 | Xpress weiss | 3996,00 |
2 | STZBG | 4 | Xpress schwarz | 3996,00 |
[
{
"module": "Flex",
"positionen": [
{
"Position": 0,
"ID": {
"id": "XLEW_1_2_2",
"wert": "STZBH"
},
"Menge": {
"id": "XLEW_1_2_5",
"wert": "2"
},
"Bezeichnung": {
"id": "XLEW_1_2_6",
"wert": "Xpress weiss"
},
"BP_Gesamt": {
"id": "XLEW_1_2_17",
"wert": "1998,00"
}
},
{
"Position": 1,
"ID": {
"id": "XLEW_1_2_2",
"wert": "STZBH"
},
"Menge": {
"id": "XLEW_1_2_5",
"wert": "5"
},
"Bezeichnung": {
"id": "XLEW_1_2_6",
"wert": "Xpress weiss"
},
"BP_Gesamt": {
"id": "XLEW_1_2_17",
"wert": "3998,00"
}
}
]
},
{
"module": "Flex",
"positionen": [
{
"Position": 0,
"ID": {
"id": "XLEW_1_2_2",
"wert": "STZBH"
},
"Menge": {
"id": "XLEW_1_2_5",
"wert": "4"
},
"BP_Gesamt": {
"id": "XLEW_1_2_17",
"wert": "3996,00"
}
},
{
"Position": 1,
"ID": {
"id": "XLEW_1_2_2",
"wert": "STZBG"
},
"Menge": {
"id": "XLEW_1_2_5",
"wert": "4"
},
"Bezeichnung": {
"id": "XLEW_1_2_6",
"wert": "Xpress schwarz"
},
"BP_Gesamt": {
"id": "XLEW_1_2_17",
"wert": "3996,00"
}
}
]
}
]
I'm new to Angular and mat-table and couldn't find a solution for my problem.
Can someone help me
CodePudding user response:
You need to install underscore.js in your project and then you can use this code
<ng-container *ngFor="let td of table_data">
<h1>{{td.name}}</h1>
<table mat-table [dataSource]="td.data" >
<ng-container [matColumnDef]="column" *ngFor="let column of td.header">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="td.header"></tr>
<tr mat-row *matRowDef="let row; columns: td.header;"></tr>
</table>
parseData(inputArray: any[]) {
const returnArray = [];
for (const data of inputArray) {
const new_obj = { name: "", header: [], data: [] };
const arr = [];
new_obj["data"] = [];
new_obj["name"] = data.module;
for (const d of data.positionen) {
const keys = Object.keys(d);
const obj: any = {};
for (const k of keys) {
if (k === "Position") {
obj[k] = d[k];
} else {
obj[k] = d[k].wert;
}
}
new_obj["data"].push(obj);
arr.push(keys);
}
new_obj["header"] = _.uniq(_.flatten(arr));
returnArray.push(new_obj);
}
return returnArray;
}
ngOnInit(): void {
this.table_data = this.parseData(PASS_YOUR_DATA_HERE);
}