使用Angular将动态行添加到HTML表中 [英] Dynamically adding rows using components into HTML table with Angular

查看:1099
本文介绍了使用Angular将动态行添加到HTML表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个奇怪的问题,我不明白为什么会发生。
我想使用Angular 4呈现HTML表格。



如果我使用下面的语法输出表格,那么一切正常

 < tbody> 
< tr * ngFor =让运动员的运动员>
< td>< / td>
< td> {{athlete.name}}< / td>
< td> {{athlete.country}}< / td>
< td> {{athlete.time}}< / td>
< / tr>
< / tbody>

表格呈现正确:



然而,如果将同一行放置到组件的表中,该组件在表格中的显示不正确Chrome(但在Edge中是正确的)。

 < tbody> 



难道这是因为在查看Google开发工具时,呈现DOM是这样的事实?



我也尝试将< tr> * ngFor 在组件外,但问题始终是相同的。



我在Plunkr上重现了这个问题: https://plnkr.co/FZAFEP5S8KhzvdKwBtbH

解决方案

使用您的组件的属性选择器

athlete.component.ts

  @Component({
selector:'tr [app-athlete]',
template:`
< td>< / td>
< td> {{athlete.name}}< / td>
< td> {{athlete.country}}< / td>
< td> {{athlete.time}}< / td>
`,
})

导出类AthleteComponent {
@Input()运动员:运动员;
}

现在,父组件的模板应该如下所示:

 < tr app-athlete [运动员] =运动员* ngFor =让运动员的运动员> 
< / tr>

Plunker Example


I'm encountering a strange problem and I cannot understand why it's happening. I want to render an HTML table using Angular 4.

If I output the table using the following syntax everything works fine

<tbody>
    <tr *ngFor="let athlete of athletes">
        <td></td>
        <td>{{athlete.name}}</td>
        <td>{{athlete.country}}</td>
        <td>{{athlete.time}}</td>
    </tr>
</tbody>

And the table is rendered correctly:

But if do the same thing delegating the rending of the row to a component the table is not rendered correctly in Chrome (but is correct in Edge).

<tbody>
    <app-athlete [athlete]="athlete" *ngFor="let athlete of athletes">
    </app-athlete>
</tbody>

athlete.component.html

<tr>
    <td></td>
    <td>{{athlete.name}}</td>
    <td>{{athlete.country}}</td>
    <td>{{athlete.time}}</td>
</tr>

Could it be due to the fact that the "rendered" DOM is something like this when looking at Google Dev tools?

I also tried putting the <tr> with the *ngFor outside of the component but the problem is always the same.

I've reproduced the problem on Plunkr: https://plnkr.co/FZAFEP5S8KhzvdKwBtbH

解决方案

Use attribute selector for your component

athlete.component.ts

@Component({
  selector: 'tr[app-athlete]',
  template: `
    <td></td>
    <td>{{athlete.name}}</td>
    <td>{{athlete.country}}</td>
    <td>{{athlete.time}}</td>
  `,
})

export class AthleteComponent {
  @Input() athlete: Athlete;
}

Now template of parent component should look like:

<tr app-athlete [athlete]="athlete" *ngFor="let athlete of athletes">
</tr>

Plunker Example

这篇关于使用Angular将动态行添加到HTML表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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