Angular 5: Как отобразить массив объектов в html * ngFor - PullRequest
0 голосов
/ 03 сентября 2018

У меня есть массив объектов, как показано ниже:

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. Я гуглил эту проблему, но не получил подходящий ответ.

1 Ответ

0 голосов
/ 03 сентября 2018

Вы не упомянули ни одного названия отдела в вашем коде. Я добавил несколько названий отделов для заполнения данных.

Пример кода:

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'}
        ]
    },
];

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

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...