Nested loops in angular 2
I want to display the data of this array:
array = [
{nom: nom1, composants: [composant11, composant12]},
{nom: nom2, composants: [composant21, composant22]}
]
I want to show it this way in a table:
composer nom
composant11 nom1
composant12 nom1
composant21 nom2
composant22 nom2
This is my code:
<table>
<tr>
<th>Composant</th>
<th>Nom</th>
</tr>
<template *ngFor="let item of array">
<template *ngFor="let composant of item.composants">
<tr>
<td>{{composant.nom}}</td>
<td>{{composant.code}}</td>
</tr>
</template>
</template>
</table>
My browser doesn't show anything. I wonder if there really is a way to do this in a template. Or if I must first convert the array to a component before displaying it. Any suggestion would be appreciated!
+3
edkeveked
source
to share
3 answers
Try the following:
rows = [
{nom: "nom1", composants: ["composant11", "composant12"]},
{nom: "nom2", composants: ["composant21", "composant22"]}
];
<table>
<ng-container *ngFor="let row of rows">
<tr *ngFor="let composant of row.composants">
<td> {{ composant }} </td>
<td> {{ row.nom }} </td>
</tr>
<ng-container>
</table>
+9
Faly
source
to share
I am using slightly different syntax which did the job
http://plnkr.co/edit/Z94BxYiu2UTU7h3oySui?p=preview
<table>
<tr>
<th>Composant</th>
<th>Nom</th>
</tr>
<template ngFor #item [ngForOf]="array">
<template ngFor #noo [ngForOf]="item.composants">
<tr>
<td>{{noo}}</td>
<td>{{item.nom}}</td>
</tr>
</template>
</template>
</table>
+1
Milan
source
to share
Modify the code as shown below:
<table>
<tr><th>Composant</th>
<th>Nom</th>
</tr>
<template *ngFor="let item of array">
<template *ngFor="let composant of item.composants">
<tr> <td>{{item.nom}}</td> <td>{{composant|json}}</td>
</tr>
</template>
</template>
</table>
0
vishal paalakurthi
source
to share