What is the best way to loop through an array inside an object stored within another array using *ngFor in Angular 2?

Overview:

My game data is structured as an array called 'game' with seven objects representing each round. Each round object contains details like 'roundNumber', 'title', 'players', and 'winner'. The 'players' property is an array of objects for each player, including their score for the 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,
   },

    // Additional round objects
    // Additional round objects
    // Additional round objects

];

Goal:

I aim to efficiently display this data in a table on my template using *ngFor loop in Angular.

<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 round of game">
        <td *ngFor="let player of round.players">{{ player.score }}</td>
      </tr>
    </tbody>
  </table>

I've successfully iterated through each round but encountered difficulty looping through each player within each round. Any guidance on structuring the loop would be highly appreciated. I envision the final output to resemble this: https://i.sstatic.net/cHvWo.png

Answer №1

For each round in TR, iterate through the players and display their scores.

 <tr *ngFor="let round of game">
   <td *ngFor="let player of round.players">{{ player.score }}</td>
 </tr>

Please ensure that your rounds and players data are structured consistently within each array. Good luck!

Answer №2

Implement the extended syntax of *ngFor in this scenario:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

Steps for combining two collections into a single output in MongoDB with Node.js

My MongoDB collections consist of data that I need to merge using the $lookup operation. However, the result I get contains a nested array structure that is not ideal. I am looking for a solution to format the result as shown below: First collection locati ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

Send a quick message with temporary headers using Express Post

When creating a response for a post request in Express that returns a simple text, I encountered an issue. var express = require('express'); var app = express(); var bodyParser = require("body-parser"); var multer = require('multer') ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

Is it possible to utilize window.location.replace function within an iframe?

Is it possible to use window.location.replace to bypass history and target on-page anchors without page reloads, but encounter issues when working within iframes? The main problem seems to be a CSP (content security policy) violation for script-src ' ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

How to choose multiple images in Ionic framework

I am working with the following HTML structure: <div ng-repeat="image in images"> <img ng-src="img/{{image}}_off.png" /> </div> Additionally, I have the following JavaScript code in the controller: $scope.images = ['imga',&ap ...

Struggling with combining model and textures in three.js

Here in this fiddle, you can find an example of the issue I am facing: http://jsfiddle.net/saward/78Bjk/7/ If you uncomment scene.add(tree_mesh) and scene.add(mesh2), and comment out scene.add(mesh), you will be able to see both objects. However, when I m ...

Difficulties with toggling jQuery menus

I am trying to create a sidebar that will appear with a full screen fade over the entire page when I click on the 'navigate' text. Currently, the sidebar appears and my header text moves to the left. However, I am struggling to make it responsiv ...

Is there a way to obtain metadata for a specific link?

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><$BlogPageTitle$></title> <meta property="og:title" content=" ...

The only React element that is rendered inside a for loop is the last one

I'm struggling with a function that is supposed to render an infinite number of strings as Comment components, but it only displays the last component. This is the function I'm working with: function displayComments(...comments) { for(let i ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

The error message "element.getAttribute is not defined" is common when using the Perfect

I'm facing an issue while trying to implement the perfect-scrollbar plugin on my AngularJS website. The error I encounter is as follows: TypeError: element.getAttribute is not a function at getId (http://localhost/Myproject/js/lib/perfect-scrollb ...

Parsing JSON objects with identifiers into TypeScript is a common task in web development

I possess a vast JSON object structured like so: { "item1": { "key1": "val1", "key2": "val2", "key3": [ "val4", "val5", ] }, { "item2": { "key1": "val1", "ke ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to ...

behavior of the back button within an AngularJS program

Currently facing an issue with a single-page application built using AngularJS. The app is composed of three main views - the login view, main view, and logout view. myapp/#/login myapp/#/main myapp/#/logout This is my route provider setup: function Ro ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...