Angular 8、渲染一个基于table的组件,不包含标签

Angular 8, rendering a table-based component without enclosing tags

这是我想要完成的。我的 HTML 页面上有一个 table 元素。 table 具有复杂的行结构。每三行与一个数据项相关。现在,table 是硬编码的 HTML 并且非常 complex/messy 看起来,所以我想制作一个组件来代替许多 tr 元素,还允许我更干净地使用 *ngIf。

所以,为了清楚起见,我删除了所有 tdtbody[=42=,而不是这个(现有的 HTML ] 和为简单起见的其他标签):

<table>
  <tr>Item1</tr>
  <tr>Item1</tr>
  <tr>Item1</tr>
  <tr>Item2</tr>
  <tr>Item2</tr>
  <tr>Item2</tr>
  <tr>Item3</tr>
  <tr>Item3</tr>
  <tr>Item3</tr>
</table>

我想用这个:

<table>
  <app-row item="item1"></app-row>
  <app-row item="item2"></app-row>
  <app-row item="item3"></app-row>
</table>

或类似这样的内容:

<table>
  <app-row *ngFor="let item of items"></app-row>
</table>

问题来了

当我尝试使用组件执行此操作时,我最终得到的是这个。它有组件标签包裹在 tr 元素的每个部分。这不仅是不正确的 HTML,而且它破坏了 CSS 选择器,它期望 table 看起来像 table>tr>td .

<table>
  <app-row>
    <tr>Item1</tr>
    <tr>Item1</tr>
    <tr>Item1</tr>
  </app-row>
  <app-row>
    <tr>Item2</tr>
    <tr>Item2</tr>
    <tr>Item2</tr>
  </app-row>
  <app-row>
    <tr>Item3</tr>
    <tr>Item3</tr>
    <tr>Item3</tr>
  </app-row>
</table>

我做了一些调查,似乎每个人都建议改用 "attribute selector",它可能看起来像这样:

<table>
  <tr appRow item="item1"></tr>
  <tr appRow item="item2"></tr>
  <tr appRow item="item3"></tr>
</table>

然而,这会导致在所有情况下都有双 tr 标签。

<table>
    <tr>
        <tr>Item1</tr>
        <tr>Item1</tr>
        <tr>Item1</tr>
    </tr>
      <tr>
        <tr>Item2</tr>
        <tr>Item2</tr>
        <tr>Item2</tr>
      </tr>
      <tr>
        <tr>Item3</tr>
        <tr>Item3</tr>
        <tr>Item3</tr>
      </tr>
</table>

任何人都可以推荐一种创建此结构的方法,以便我在没有附加标签的情况下获得正确的结果 HTML 吗?

使用 属性选择器 也是一种解决方案,但您必须将属性应用于 <table> 并让组件生成 <tr>s .

<table appRow *ngFor="let item of items" [itemInput]="item">
</table>