簡體   English   中英

如何在angular 2中使用* ngFor遍歷數組中對象的數組?

[英]How do I iterate over an array within an object within an array using *ngFor in angular 2?

背景:

我有一個稱為游戲的數組,它由代表游戲中每一輪的七個對象組成。 在每個對象中,我都有關於該回合的詳細信息,例如“ roundNumber”,“ title”,“ players”和“ winner”。 “玩家”屬性是“玩家”對象的數組,其中包含該玩家在特定回合中的得分。

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

];

我想發生的事情:

我希望能夠遍歷所有這些數據,並使用* 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>

如您所見,我遍歷了頂級數組,但我不知道如何在每一輪中遍歷每個玩家。 任何幫助將不勝感激。 它看起來應該像這樣: 在此處輸入圖片說明

循環遍歷每個玩家的TR和td。

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

請注意,每個陣列的運氣和玩家數據都應采用相同的方式。

您可以在此處使用* ngFor的擴展語法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM