Angular2 组件以循环方式呈现两个 tr 元素

4

我需要编写一个组件,其模板应如下所示:

<tr>...</tr>
<tr>...</tr>

这必须与*ngFor一起使用来创建表格。 该组件的选择器是spot-row。 该组件有一个名为spot的输入变量。

期望的输出应如下所示:

<table>
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
<table>

我尝试了以下内容:
<table>
<tbody>
<spot-row *ngFor="let spot of spots" [spot]="spot"></spot-row>
</tbody>
<table>

但是这个产生了

<table>
<tbody>
<spot-row>
<tr>...</tr>
<tr>...</tr>
</spot-row>
</tbody>
<table>

然后我尝试将组件选择器切换为 [spot-row] 并使用 ng-container

<table>
<tbody>
<ng-container spot-row *ngFor="let spot of spots" [spot]="spot"></ng-container>
</tbody>
<table>

但是这导致了一个错误

错误:Error in ./SpotRowComponent class SpotRowComponent - inline template:0:0 caused by: Failed to execute 'appendChild' on 'Node': This node type does not support this method

然后我尝试使用template

<table>
<tbody>
<template spot-row *ngFor="let spot of spots" [spot]="spot"></template>
</tbody>
<table>

但这也给我带来了一个错误

错误:模板解析错误:嵌入式模板上的组件:SpotRowComponent(" [ERROR ->] ")

我在StackOverflow上搜索并发现了以下内容:


也许您可以使用<tbody>作为包装元素?应该是有效的HTML。(删除外部的<tbody> - Arg0n
1个回答

3

根据评论提供的建议,此内容未经测试。

组件选择器:[spot-row]

组件模板:

<tr>...</tr>
<tr>...</tr>

HTML:

<table>
   <tbody *ngFor="let spot of spots" spot-row [spot]="spot"></tbody>
<table>

这应该产生:

<table>
   <tbody>
     <tr>...</tr>
     <tr>...</tr>
   </tbody>
   <tbody>
     <tr>...</tr>
     <tr>...</tr>
   </tbody>
   ...
</table>

哪种情况是有效的(在<table>中有多个<tbody>).

tbody方法并不完美,但它是可行的。模板方法会生成错误,正如我在问题中提到的那样。 - wertzui
@wertzui 抱歉,我在你的问题中漏掉了那一部分。 - Arg0n

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接