簡體   English   中英

Angular 5:如何通過 *ngFor 在 html 中顯示對象數組

[英]Angular 5: How to display array of objects in html by *ngFor

我有如下對象數組:

app.component.ts:

this.documents=[
  { employees: [ {name: "John Smith", age: 28},
                 {name: "Sarah Johnson", age: 32},
                 {name: "Mark Miller", age: 46} 
               ]
  },
  { employees: [ ] },
  { employees: [ {name: "Jimmy Colleen", age: 35},
                 {name: "Olivia Powell", age: 37}
               ] 
  },       
]

app.component.html:

         <table class="table table-striped">
            <thead>
              <tr>
                <th scope="col">Department</th>
                <th scope="col">Name</th>
                <th scope="col">Age</th>
              </tr>
            </thead>
            <tbody *ngIf="documents.length">
              <tr *ngFor="let doc of documents; let i = index">
                <td>Department {{i + 1}}</td>
                <td>Name {{}}</td>
                <td>Age {{}}</td>
              </tr>
            </tbody>
          </table>

我的問題是如何在 HTML 中為每個部門顯示不同的名字和他們的年齡。 我用谷歌搜索了這個問題,但沒有得到合適的答案。

您沒有在代碼中提及任何部門名稱。 我添加了一些部門名稱來填充數據。

示例代碼:

app.component.ts

documents = [
    { employees: [ {name: 'John Smith', age: 28, department: 'IT'},
            {name: 'Sarah Johnson', age: 32, department: 'IT'},
            {name: 'Mark Miller', age: 46, department: 'IT'}
        ]
    },
    { employees: [ ] },
    { employees: [ {name: 'Jimmy Colleen', age: 35, department: 'ADMIN'},
            {name: 'Olivia Powell', age: 37, department: 'ADMIN'}
        ]
    },
];

應用程序組件.html

 <table class="table table-striped">
   <thead>
     <tr>
       <th scope="col">Department</th>
       <th scope="col">Name</th>
       <th scope="col">Age</th>
     </tr>
   </thead>
   <ng-container *ngIf="documents.length">
      <tbody *ngFor="let doc of documents; let i = index">
        <tr *ngFor="let employee of doc.employees;">
          <td>{{employee.department}}</td>
          <td>{{employee.name}}</td>
          <td>{{employee.age}}</td>
        </tr>
      </tbody>
    </ng-container>
  </table>

希望這可以幫助 !

暫無
暫無

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

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