piernik
piernik

Reputation: 3657

Rendering ng-content multiple times

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??

Upvotes: 3

Views: 2192

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

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.

Upvotes: 5

Related Questions