创建一个Angular组件以显示要嵌入其他表的一组html表格单元格

Jer*_*emy 5 html angular-template angular-components angular

我有很多html表共享相同的15列以及特定于每个表的自定义列.我想创建这些常见的15列作为一个组件,它接收一组数据并显示为没有包装器的15 td.我无法弄清楚如何创建一个Angular组件,它不会在DOM中显示包装器标签,并允许我传入输入.以下是我想做的事情:

<tr *ngFor="let item of items">
  <td>Column 1</td>
  <my-common-columns [data]="item"></my-common-columns>
  <td>Another column</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

不幸的是,使用上面的代码,<my-common-columns>标记显示在渲染的DOM中,这会弄乱表格.我只能tdtr标签下面.

我也试过,<ng-container *ngComponentOutlet="myCommonColumns">因为ng-container没有出现在DOM中,但我无法弄清楚如何传入data它.

Ili*_*olk 5

import { Component, TemplateRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-common-columns',
  template: `<ng-template let-item>
  <td>inner item1:{{item}}</td>
  <td>inner item2:{{item}}</td>
  </ng-template>`
})
export class CommonComponent {
  @ViewChild(TemplateRef) template: TemplateRef<any>;
}


@Component({
  selector: 'my-app',
  template: `
  <table>
    <tr *ngFor="let item of data">
      <td>first</td>
      <ng-template [ngTemplateOutlet]="common.template"
                 [ngTemplateOutletContext]="{$implicit: item}">
      </ng-template>
      <td>last</td>
    </tr>
  </table>
<my-common-columns #common></my-common-columns>
  `
})
export class AppComponent  {
  data = [1, 2, 3, 4, 5];
}
Run Code Online (Sandbox Code Playgroud)

活生生的例子

结果:

结果

ngComponentOutlet也会在 HTML 中显示标签。或者,您应该使用抽象来显示复杂问题的表格。