Reputation: 456
Background:
I have an array called game that consists of seven objects that represent each round in the game. Within each object I have details about that round such as 'roundNumber', 'title', 'players', and 'winner'. The 'players' property is an array of 'player' objects which contains the score for that player on that particular round.
game = [
{
roundNumber: 1,
title: "2 Books",
players: [
{
pk: 1,
username: "James",
score: 5,
},
{
pk: 2,
username: "Jim",
score: 54,
},
{
pk: 3,
username: "Bob",
score: 22,
},
],
winner: undefined,
},
{
roundNumber: 2,
title: "1 Book 1 Run",
players: [
{
pk: 1,
username: "James",
score: 54,
},
{
pk: 2,
username: "Jim",
score: 32,
},
{
pk: 3,
username: "Bob",
score: 76,
},
],
winner: undefined,
},
//etc
//etc
//etc
];
What I want to happen:
I want to be able to loop through all of this data and place it in a table on my template using *ngFor.
<table id="data-table" class="table table-striped">
<thead>
<tr>
<th *ngFor="let round of game">{{ round.title }}</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let player of round of game"> //HOW DO I STRUCTURE MY LOOP HERE?
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
</tr>
</tbody>
</table>
As you can see, I've looped though the top level array but I don't know how to loop through each player on each round. Any help would be greatly appreciated. It should look something like this:
Upvotes: 0
Views: 3019
Reputation: 1615
You can use the extended syntax of *ngFor here:
<table id="data-table" class="table table-striped">
<ng-template ngFor let-round [ngForOf]="game">
<thead>
<tr>
<th>{{ round.title }}</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let player of round.players">
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
</tr>
</tbody>
</ng-template>
</table>
Upvotes: 1
Reputation: 2905
Loop though each rounds in TR and td for each player.
<tr *ngFor="let round of game">
<td *ngFor="let player of round.players">{{ player.score }}</td>
</tr>
Upvotes: 5