在 Angular 2 模板中的 table 中显示一行及其子行

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

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

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

table 应包含以下行:

 bag
 pen
 pen1
 chair

请帮忙。

您可以展平项目数组:

@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

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