1

I want to be able to have to option of adding icons/progress-bar in the rows of my reusable Angular table component, however I am having a hard time implementing this. I've tried adding ng-content in my table.component.html, however this only projects content once. How would I approach this?

table.component.html

<table>
    <thead>
        <tr>
            <th *ngFor="let col of cols" 
            (click)="selectColHeader(col.prop); 
            col.enableSort && sort(col.prop)">
                {{col.header}}
                <input type="text"
                class="ds-c-field"
                [(ngModel)]=fields[col.prop] 
                (click)="selectColInput(col.prop, $event)"
                *ngIf=col.enableFilter/>
                <img 
                class="arrow"
                *ngIf="col.enableSort && col.prop === selectedColHeader"
                [src]="direction === 'asc' ? upArrowPath : downArrowPath"/>
            </th>
        </tr>
    </thead>
    <tbody *ngFor="let row of data">
        <tr>
            <td *ngFor="let col of cols">
                {{row[col.prop]}}
                <ng-content></ng-content> 
                //icon projected here
            </td>
        </tr>
    </tbody>
</table>

app.component.html

<app-data-table [data]=data [cols]=cols>
    <img src="#"/> //custom icon or progress-bar here
</app-data-table>
1

1 Answer 1

1

I think you are looking for ngTemplateOutlet

custom-table.component.html

<table>
    <thead>
        <tr>
            <th *ngFor="let col of cols">
                {{col.prop}}
            </th>
        </tr>
    </thead>
    <tbody *ngFor="let row of rows">
        <tr>
            <td *ngFor="let col of cols">
                {{row[col.prop]}}
                <ng-container *ngTemplateOutlet="cellTemplate"></ng-container>
            </td>
        </tr>
    </tbody>
</table> 

custom-table.component.ts

@Input() cellTemplate: TemplateRef<any>;

Then in the parent component do like, for example app.component.html

<app-custom-table [cellTemplate]="cellTemplate">
  <ng-template #cellTemplate>
    <div> custom content </div> <!-- Inject content as you like -->
  </ng-template>
</app-custom-table>

And that's it. You can checkout the sample code in stackblitz

For more insight into ngTemplateOutlet, ng-container and ng-template, see this great article https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.