I am trying to iterate the list in form of table. The following list should be rendered in the form of table using *ngFor
:
I/p :
let list = [
{
"key1": {
"subkey1": [
1,
2,
3,
1
],
"subkey2": [
3,
2,
3,
4
]
}
},
{
"key2": {
"subkey1": [
1
],
"subkey2": [
0
]
}
}
]
Table format (This is how table should render) :
Categories | subkey1 | subkey2
key1 | 1,2,3,1 | 3,2,3,4
key2 | 1 | 0
I tried but its wrong :
Code I tried to iterate in component.html :
<table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th> // Array of subkeys
</tr>
</thead>
<tbody *ngFor="let each of categoriesList">
<tr>
<td *ngFor="let key of objectKeys(each)">// iterating keys
{{key}}
</td>
<td> </td> // I don't know how to itereate the values of each subkey of key [1,2,3]
</tr>
</tbody>
</table>
I was not able to share StackBlitz. So I'm sharing this screenshot :
Please let me know if something is missing.
You can arrange the data as required and then display it in template.
Try like this:
Working Demo
Controller:
categoriesHeading = [];
displayData = [];
constructor() {
this.categoriesHeading = Object.keys(this.list[0].key1);
this.list.forEach(item => {
let obj = {};
obj["key"] = Object.keys(item)[0];
Object.keys(item[Object.keys(item)[0]]).forEach((subkey, i) => {
obj[subkey] = item[Object.keys(item)[0]][subkey].join();
});
this.displayData.push(obj);
});
}
Template:
<table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of displayData">
<td *ngFor="let each of item | keyvalue"> {{each.value}} </td>
</tr>
</tbody>
</table>
NOTE: For Angular 4, if you don't want to use (keyvalue pipe), then do the following.
TS:
objectKeys = Object.keys;
Template:
<table border="1">
<thead>
<tr>
<th>Categories</th>
<th *ngFor="let each of categoriesHeading"> {{each}} </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of displayData">
<td *ngFor="let key of objectKeys(item)"> {{item[key]}} </td>
</tr>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With