Angular2:渲染一个没有包装标签的组件 [英] Angular2 : render a component without its wrapping tag
问题描述
我正在努力寻找一种方法来做到这一点.在父组件中,模板描述了 table
及其 thead
元素,但将渲染 tbody
委托给另一个组件,如下所示:>
I am struggling to find a way to do this. In a parent component, the template describes a table
and its thead
element, but delegates rendering the tbody
to another component, like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Time</th>
</tr>
</thead>
<tbody *ngFor="let entry of getEntries()">
<my-result [entry]="entry"></my-result>
</tbody>
</table>
每个 myResult 组件呈现自己的 tr
标签,基本上像这样:
Each myResult component renders its own tr
tag, basically like so:
<tr>
<td>{{ entry.name }}</td>
<td>{{ entry.time }}</td>
</tr>
我没有把它直接放在父组件中(避免需要 myResult 组件)的原因是 myResult 组件实际上比这里显示的更复杂,所以我想把它的行为放在一个单独的组件中,并且文件.
The reason I'm not putting this directly in the parent component (avoiding the need for a myResult component) is that the myResult component is actually more complicated than shown here, so I want to put its behaviour in a separate component and file.
生成的 DOM 看起来很糟糕.我相信这是因为它无效,因为 tbody
只能包含 tr
元素 (参见 MDN),但我生成的(简化的)DOM 是:
The resulting DOM looks bad. I believe this is because it is invalid, as tbody
can only contain tr
elements (see MDN), but my generated (simplified) DOM is :
<table>
<thead>
<tr>
<th>Name</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<my-result>
<tr>
<td>Bob</td>
<td>128</td>
</tr>
</my-result>
</tbody>
<tbody>
<my-result>
<tr>
<td>Lisa</td>
<td>333</td>
</tr>
</my-result>
</tbody>
</table>
有什么方法可以让我们渲染相同的东西,但没有包装 <my-result>
标签,同时仍然使用一个组件来单独负责渲染表格行?
Is there any way we can get the same thing rendered, but without the wrapping <my-result>
tag, and while still using a component to be sole responsible for rendering a table row ?
我查看了 ng-content
、DynamicComponentLoader
、ViewContainerRef
,但它们似乎没有为此提供解决方案据我所知.
I have looked at ng-content
, DynamicComponentLoader
, the ViewContainerRef
, but they don't seem to provide a solution to this as far as I can see.
推荐答案
你可以使用属性选择器
You can use attribute selectors
@Component({
selector: '[myTd]'
...
})
然后像这样使用
<td myTd></td>
这篇关于Angular2:渲染一个没有包装标签的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!