在Angular 2模板

时间:2017-04-24 13:00:21

标签: angular angular2-template ngfor

我在项目中使用Angular 2。我遇到了一个场景,其中我有一个项目列表,一个项目可能有子项目。我必须显示表格中的所有项目(包括子项目)。我在tr标签中为每个项目列表使用了* ngFor。但是,因为,我还必须显示子项目,我无法通过一个* ngFor来做到这一点。我可以采取什么方法来实现这一目标?寻找你的建议。请帮帮我。这是我想要展示的内容。

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

该表应包含以下行:

 bag
 pen
 pen1
 chair

请帮忙。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

您可以展平您的项目数组:

@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