Home > Enterprise >  Angular table row not spanning table as expected?
Angular table row not spanning table as expected?

Time:10-14

I have a very simple Angular app that creates a table of items, say "products".

I have a component called "Products" and a sub-component (if that is the terminology) called product-item.

My problem is with the column span of rows from the sub-component. As a test I did the following to show my issue:

In the "Products" component, I have the following HTML:

<table [ngClass]="{'blueTable':true}">
    <thead>
        <tr>
        <th>head1</th>
        <th>head2</th>
        <th>head3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>test c1</td>
            <td>test c2</td>
            <td>test c3</td>
        </tr>
        <!-- <ng-container *ngFor="let docketItem of docketList"> -->
        <ng-container *ngFor="let number of [0,1,2]">
            <app-product-item></app-product-item>
        </ng-container>
    </tbody>
    <tfoot>
        <tr>
            <td>foot 1</td><td>foot 2</td><td>foot 3</td>
        </tr>
    </tfoot>
</table>

In the "product-item" component, I have the following HTML:

<tr>  
  <td>cA</td>
  <td>cB</td>
  <td>cC</td>
</tr>

This is the output:

sample output table

My goal is that each product-item row is a new row in the table. What am I not understanding?

CodePudding user response:

A tr element must be a direct child of table element or of thead/tbody/tfoot

If you will check in your DOM, you have inside the tbody an app-product-item element that contains the tr

I assume you tried to fix by using ng-container and that's why you didn't do simply:

<app-product-item *ngFor="let number of [0,1,2]"></app-product-item>

But still the tr is inside the app-product-item

You should use attribute selector, and then in the "Products" component, have the following:

<tbody>
  <tr *ngFor="let number of [0,1,2]"></tr>
</tbody>

In the "product-item" component, get rid of the tr

And in the "product-item" ts file, change the selector to:

@Component({
  selector: '[app-product-item]',
  ...
  • Related