自定义角度组件不会在模板中呈现为TR

Kon*_*ten 5 html css html-table angular

我正在重新设计一个表,我想引入自己的自定义组件而不是默认的TR元素.该表按预期工作,看起来像这样.

<table>
  <thead>
    <tr><th *ngFor="let column of this.columns">{{column.title}}</th></tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of this.rows"></tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

然后,我介绍了我自己的组件来替换通常的TR并将网格的标记切换到以下.

<table>
  <thead>
    <tr><th *ngFor="let column of this.columns">{{column.title}}</th></tr>
  </thead>
  <tbody>
    <row *ngFor="let row of this.rows" [value]="row" [formats]="columns"></row>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

新组件的标记非常简陋,如下所示.

<td *ngFor="let format of formats">
  {{value[format.id]}}
</td>
Run Code Online (Sandbox Code Playgroud)

它有效,有点.即我可以看到值,生成的TD(我可以确认检查devtools)在表的第一列中呈现.所以数据绑定有效.标记的生成起作用.唯一失败的是愚蠢的浏览器没有得到ROW应该是一行(就像TR一样).它认为它可以呈现为单个TD.

我怎么告诉愚蠢的浏览器做我的意思,而不是我说的?

SrA*_*Axi 6

我认为这是因为它不能识别row为a tr,因此它无法正确呈现table.

尝试使用这样的组件:

@Component({ 
   selector: '[row]',
   template: `
   <td *ngFor="let format of formats">
      {{value[format.id]}}
   </td>
   ` 
})
Run Code Online (Sandbox Code Playgroud)

然后在你的表中:

<tr row></tr>
Run Code Online (Sandbox Code Playgroud)

这样,每个人都认为它tr是一个tr但它会表现得像你想要的那样:使用你的row组件.

(我对自定义菜单元素有同样的问题.它无法识别li元素.使用<li my-element>修复问题.)

  • @KonradViltersten不,是我写了*“这叫做Attribute指令” *,那是不正确的,他指出了这一点,并从答案中删除了它。为什么我在之前的评论中解释的说法不正确。如果您希望保持HTML标记完整,则通常将*组件作为属性进行调用。所以,不用担心。只要意识到通过像调用指令一样调用您的组件就不会使它成为**属性指令**:https://angular.io/docs/ts/latest/guide/attribute-directives.html (2认同)