user3797088
user3797088

Reputation: 563

how to display the array inside an array of objects using ngFor Angular 2

I need to display the array quality which is located inside an array of objects. I have tried calling it in ngFor using the code below. Is there something wrong with my usage of ngFor?

import { Component} from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<table>
                  <thead>
                    <tr>
                       <th>Name</th>
                       <th>Quality1</th>
                       <th>Quality2</th>
                    </tr>
                  </thead>
                  <tbody>
                      <tr *ngFor"let item of people">
                         <td>{{item.Name}}</td>
                         <td *ngFor"let item of people.quality">item.quality1</td>
                         <td *ngFor"let item of people.quality">item.quality2/td>
                       </tr>
                  </tbody>
              </table>
   })

  export class AppComponent{    
     people: any = [{Name:"John", quality:[{quality1: "nice", quality2: "humble"}]}, {Name:"Dave", quality:[{quality1: "kind", quality2: "caring"}]} ];
  }

As of now only the names are appearing in the table but I would also like the quality to appear.

Upvotes: 5

Views: 15368

Answers (3)

Anoop P S
Anoop P S

Reputation: 782

We can simply iterate the loop inside by modifying the second loop

        <tr *ngFor="let item of people">
            <td>{{item.Name}}</td>
            <td *ngFor="let quality of item.quality">{{ quality }}</td>
            <td *ngFor="let quality2 of item.quality2">{{quality2}}</td>
        </tr>

Upvotes: 2

Emile Cantero
Emile Cantero

Reputation: 2063

If I understand you well you could also bind like that:

                   <tr *ngFor="let item of people">
                     <td>{{item.Name}}</td>
                     <td *ngFor="let item of people.quality">{{item.quality.[quality1]}}</td>
                     <td *ngFor="let item of people.quality">{{item..quality.[quality2]}}</td>
                   </tr>

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658057

You can use <ng-container> to combine several nodes with *ngFor without introducing another element to the DOM:

<ng-container *ngFor"let item of people.quality">
  <td>item.quality1</td>
  <td>item.quality2/td>
</ng-container>

Upvotes: 0

Related Questions