7

I have an angular component that I want to use in a table with an ngFor but it breaks the table layout. My table looks like:

<table class="table table-stripped">
  <thead>
    <th style="width: 30%;">Network</th>
    <th style="width: 10%;">Quantity</th>
    <th style="width: 30%;">Supplier</th>
    <th style="width: 30%;">Conn Type</th>
    <th></th>
  </thead>
  <tbody>
    <tr *ngFor="let prod of opportunity.products; let i = index;">
      <app-product-row [product]="prod"></app-product-row>
    </tr>
  </tbody>
</table>

the child component looks like:

<td style="width: 30%;">
...
</td>
<td  style="width: 10%;">
...
</td>
<td style="width: 30%;">
...
</td>
<td style="width: 30%;">
...
</td>
<td>
...
</td>

but all of the child component s are placed in the first td element because angular is putting in a <app-product-row ...> tag which means the s aren't rendering properly. I have tried putting the app-product-row on within the tr itself but that didn't work either.

How can I get it to render the table properly?

GrahamJRoy
  • 1,603
  • 5
  • 26
  • 56
  • you can look at https://stackoverflow.com/questions/55446740/how-to-add-row-component-in-table-in-angular-7 and https://stackoverflow.com/questions/34556277/angular2-table-rows-as-component – Caro Jun 30 '20 at 08:57
  • @GrahamJRoy:sir you fixed above issue? – Kapil Soni Aug 18 '21 at 13:30
  • The answer by Sam below worked. You need to change the selector in the child component – GrahamJRoy Aug 18 '21 at 14:19

1 Answers1

9

This is a side effect of tables being rigid in structure. You can get around this by using the component as an attribute of a native table element instead of as a component.

<tr app-product-row></tr>

You need to define the component a selector differently as well - you will need to wrap your component html in a table row.

selector: '[app-product-row]'
Sam
  • 1,736
  • 8
  • 15
  • thank you so much. it's also meant that I look at the selectors in a different way. never really thought of them in that way until you pointed out wrapping the selector with [] – GrahamJRoy Jun 30 '20 at 09:25
  • @Sam:sir in my case i have dynamically added td and i have applid above solution but its not working for mecan you please why its not working with td? – Kapil Soni Aug 18 '21 at 13:57