CodeClimber
CodeClimber

Reputation: 4191

Dynamically adding rows using components into HTML table with Angular

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:

enter image description here

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>

enter image description here

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

enter image description here

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

Upvotes: 1

Views: 1683

Answers (1)

yurzui
yurzui

Reputation: 214007

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

Upvotes: 1

Related Questions