自定义组件已注入表行

时间:2019-06-05 20:20:43

标签: html angular

我有一个在一个componentA中创建的表,该表中有多个table-row元素。然后,我有另一个componentB,它只有几个表行元素,这些元素将在模板代码中的整个应用程序中重复使用。问题在于,当在componentA表的内部使用componentB时,表行元素未跨越表的整个宽度,并且似乎在表外部损坏。

我发现了对其他几个类似问题的引用,但是它们使用的动态行基于为每一行传递的数据。我的问题是我有一组固定的行,将在整个应用程序中使用。我尝试使用以下示例:

--- componentA
<table>
 <tr><td>Name</td></tr>
 <tr componentB></tr> --- does not work
</table>

--- componentB --- selector: '[componentB]'
<tr><td>Phone Number</td></tr>
<tr><td>Email</td></tr>

--- componentA
<table>
 <tr><td>Name</td></tr>
 <componentB></componentB> --- does not work
</table>

--- componentB --- selector: 'componentB'
<tr><td>Phone Number</td></tr>
<tr><td>Email</td></tr>

以下是一个确切地说明问题的示例:https://stackblitz.com/edit/angular-ydsgaz

componentB中的元素应该像在componentA中使用的普通元素一样,跨越表格的宽度,但事实并非如此。任何帮助都会很棒!

答案:以下任一示例均适用于这种情况

1 个答案:

答案 0 :(得分:3)

使用角度内容投影。 您只需要向表主体添加指令选择器即可。 app.component.html

<table>
  <tbody app-table-rows>
    <tr>
      <td>name</td>
      <td>bob</td>
    </tr>
  <tbody>
</table>

,然后在 table-rows.component.html 中添加ng-content元素。 Angular会将ng-content元素替换为指令宿主元素中的内容。

<ng-content></ng-content>
<tr>
  <td>email</td>
  <td>bob@gmail.com</td>
</tr>
...

工作示例https://stackblitz.com/edit/angular-dr6fqs