Adding a Link/Template Column to a Custom Table Component

前端 未结 1 1578
太阳男子
太阳男子 2021-01-15 19:04

I have a table component built based off of this article: Creating an Angular2 Datatable from Scratch.

I\'ve been extending it so do different things that I need for

相关标签:
1条回答
  • 2021-01-15 19:23

    I would leverage ngTemplateOutlet to achieve it.

    Create references to possible templates for your

    column.component.ts

    @ContentChild('tableHeaderTemplate') headerTemplate: TemplateRef<any>;
    @ContentChild('tableBodyTemplate') bodyTemplate: TemplateRef<any>;
    

    So we can now use custom template for header or body if we provided it

    datatable.component.html

    <table class="table table-striped table-hover">
        <thead>
          <tr>
            <th *ngFor="let col of columns">
               <ng-container *ngIf="!col.headerTemplate">{{col.header}}</ng-container> 
               <ng-template *ngIf="col.headerTemplate" [ngTemplateOutlet]="col.headerTemplate" [ngTemplateOutletContext]="{ $implicit: { header: col.header } }"></ng-template>
            </th>
          </tr>
        </thead>
        <tbody *ngFor="let row of dataset; let i = index">
          <tr>
            <td  *ngFor="let col of columns">
              <ng-container *ngIf="!col.bodyTemplate">{{row[col.value]}}</ng-container> 
              <ng-template *ngIf="col.bodyTemplate" [ngTemplateOutlet]="col.bodyTemplate" [ngTemplateOutletContext]="{ $implicit: { value: row[col.value] }, row: row }"></ng-template>
            </td>
          </tr>
        </tbody>
    </table> 
    

    and finally table definition might look like:

    <datatable  [dataset]="photoData">
        <column [value]="'id'" [header]="'ID'"></column>
        <column [value]="'title'" [header]="'Title'">
            <ng-template #tableHeaderTemplate let-column>
                <span style="color: red">{{ column.header }}</span>
            </ng-template>
        </column>
        <column [value]="'title'" [header]="'Actions'">
          <ng-template #tableBodyTemplate let-column let-row="row">
              <button (click)="remove(row.id)">Remove {{row.id}}</button>
          </ng-template>
        </column>
    </datatable>
    

    Plunker Example

    0 讨论(0)
提交回复
热议问题