Reputation: 120
I am using Angular 2 in my project. I came across a scenario in which I have a list of items and an item may have sub items. I have to show all the items in a table (including sub items). I was using *ngFor for each item of item list in tr tag. But since, I have to display sub items also, I am not able to do this by one *ngFor. what approach can I follow to achieve this? Looking for your suggestion. Please help me out. Here is what I want to display.
items= [
{ name : 'bag', subitems: [{ name : 'pen' }, { name : 'pen1' }] },
{ name : 'chair' }
];
The table should have the following rows:
bag
pen
pen1
chair
Please help.
Upvotes: 1
Views: 2046
Reputation: 17879
<div>
<table>
<ng-container *ngFor="let item of items">
<tr>
<td>{{item.name}}</td>
<td>hi</td>
</tr>
<tr *ngFor="let subitem of item.subitems">
<td>{{subitem.name}}</td>
<td>hi</td>
</tr>
</ng-container>
</table>
</div>
Upvotes: 6
Reputation: 2884
You can flatten your array of items:
@Component({
selector: 'my-app',
template: `
<table>
<tr *ngFor="let item of flatItems">
<td>{{item.name}}</td>
</tr>
</table>
`,
})
export class App {
items= [
{ name : 'bag', subitems: [{ name : 'pen' }, { name : 'pen1' }] },
{ name : 'chair' }
];
flatItems = this.items.reduce(
(accumulator, itemValue) => {
accumulator = accumulator.concat({name: itemValue.name});
accumulator = accumulator.concat(itemValue.subitems);
return accumulator;
},
[]
);
}
Upvotes: 1