Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering ng-content multiple times

Tags:

angular

I want to create table with data but last column should be user defined with ng-content

Something like this:

<my-component [columns]="columns" [data]="data">
    <div>last column</div>
<my-component>

MyComponent.ts

<table>
    <tr *ngFor="let row of data">
        <td *ngFor="let cell of columns">{{row[cell}}</td>
        <td><ng-content></ng-content></td>
    </tr>
</table>

Problem is that last column's content is rendered only once - in last row. How to fix it??

like image 424
piernik Avatar asked Mar 23 '26 06:03

piernik


1 Answers

You cannot do that with ng-content. Try this:

table.component.ts

@Input() tpl: TemplateRef<any>;

table.component.html

<table>
  <tr *ngFor="let row of data">
    <td *ngFor="let cell of columns">{{row[cell}}</td>
      <td>
        <ng-container [ngTemplateOutlet]="tpl"></ng-container>
       </td>
  </tr>
</table>

Then you can use it like this:

<my-component [columns]="columns" [data]="data" [tpl]="lastColumn"><my-component>

<ng-template #lastColumn>
  <div>last column</div>
</ng-template>

With that being said I would take a look at Angular Material CDK table before implementing my own. You might save a lot of time that way.

like image 195
Tomasz Kula Avatar answered Mar 26 '26 00:03

Tomasz Kula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!