Angular2:渲染没有包装标签的组件 [英] Angular2 : render a component without its wrapping tag

查看:115
本文介绍了Angular2:渲染没有包装标签的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种方法来做到这一点。在父组件中,模板描述了及其 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 ?

我看了at 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.

推荐答案

你可以使用属性选择器

@Component({
  selector: '[myTd]'
  ...
})

然后使用它

<td myTd></td>

这篇关于Angular2:渲染没有包装标签的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆