Angular *ngFor create table with group item?
You can use reduce()
and filter
method to create your array as group by with group name.
I have created a demo in stackblitz. Hope this will help/guide you to achieve your requirement.
CODE SNIPPET
.ts file code
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
array = [
{
"id": 1,
"name": "item 1",
"group": "Group A"
},
{
"id": 2,
"name": "item 2",
"group": "Group A"
},
{
"id": 3,
"name": "item 3",
"group": "Group B"
},
{
"id": 4,
"name": "item 4",
"group": "Group B"
},
{
"id": 5,
"name": "item 5",
"group": "Group B"
},
{
"id": 6,
"name": "item 6",
"group": "Group C"
}
];
groupArr = this.array.reduce((r,{group})=>{
if(!r.some(o=>o.group==group)){
r.push({group,groupItem:this.array.filter(v=>v.group==group)});
}
return r;
},[]);
}
template
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tbody *ngFor="let item of groupArr">
<ng-container>
<tr >
<td colspan="2"><b>{{item.group}}</b></td>
</tr>
<tr *ngFor="let value of item.groupItem">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
</tr>
</ng-container></tbody>
</table>
You can use below logic for achieving your result.
var groups = new Set(array.map(item => item.group)),
results = [];
groups.forEach(g =>
results.push({
name: g,
values: array.filter(i => i.group === g)
}
))
HTML
<div *ngFor="let item in results">
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<ng-container>
<tr>
<td colspan="2">{{item.name}}</th>
</tr>
<tr *ngFor="let value in item.values">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
</tr>
</ng-container>
</table>
<div>
Working Stackblitz