FakeEmpire
FakeEmpire

Reputation: 798

Adding custom images to reusable Angular component

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>

Upvotes: 1

Views: 855

Answers (1)

Hoang Duc Nguyen
Hoang Duc Nguyen

Reputation: 409

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/

Upvotes: 1

Related Questions