Meenakshi Kumari
Meenakshi Kumari

Reputation: 120

To display a row and it's sub rows in a table in Angular 2 template

I am using Angular 2 in my project. I came across a scenario in which I have a list of items and an item may have sub items. I have to show all the items in a table (including sub items). I was using *ngFor for each item of item list in tr tag. But since, I have to display sub items also, I am not able to do this by one *ngFor. what approach can I follow to achieve this? Looking for your suggestion. Please help me out. Here is what I want to display.

 items= [
    { name : 'bag', subitems: [{ name : 'pen' }, { name : 'pen1' }] },
    { name : 'chair' }
  ];

The table should have the following rows:

 bag
 pen
 pen1
 chair

Please help.

Upvotes: 1

Views: 2046

Answers (2)

Julia Passynkova
Julia Passynkova

Reputation: 17879

<div>
  <table>
    <ng-container *ngFor="let item of items">
      <tr>
        <td>{{item.name}}</td>
        <td>hi</td>
      </tr>
      <tr *ngFor="let subitem of item.subitems">
        <td>{{subitem.name}}</td>
        <td>hi</td>
      </tr>
    </ng-container>
  </table>
</div> 

Upvotes: 6

hiper2d
hiper2d

Reputation: 2884

You can flatten your array of items:

@Component({
  selector: 'my-app',
  template: `
    <table>
      <tr *ngFor="let item of flatItems">
        <td>{{item.name}}</td>
      </tr>
    </table>
  `,
})
export class App {
  items= [
    { name : 'bag', subitems: [{ name : 'pen' }, { name : 'pen1' }] },
    { name : 'chair' }
  ];
  flatItems = this.items.reduce(
    (accumulator, itemValue) => {
      accumulator = accumulator.concat({name: itemValue.name});
      accumulator = accumulator.concat(itemValue.subitems);
      return accumulator;
    }, 
    []
  );
}

Plunkr

Upvotes: 1

Related Questions