Get reference of component inside ng-template

UI Components for Angular
Post Reply
dangrima90
Posts: 4
Joined: 20 Oct 2016, 10:45

16 Feb 2018, 11:24

I've created a wrapper component for PrimeNG data table to be able to handle all data table logic in one component. The component supports passing a template which is then used for expandable rows. In the template one can pass a custom template which can include another component.

Data Table Wrapper Component

Code: Select all

@Component({
  selector: 'dt-wrapper',
  template: `
    <h1>Data Table Wrapper</h1>

    <p-dataTable [value]="data" [expandableRows]="expandableRows">
        <p-column *ngIf="expandableRows" expander="true" [style]="{'width':'35px'}"></p-column>
        <p-column *ngFor="let col of columns" [field]="col.field" [header]="col.header"></p-column>
        <ng-template let-rowData pTemplate="rowexpansion">
          <ng-container *ngTemplateOutlet="rowTemplate; context: {$implicit: rowData}"></ng-container>
      </ng-template>
    </p-dataTable>
  `
})

export class DataTableWrapperComponent {
  @Input() data: any;
  @Input() columns: any;
  @Input() expandableRows: boolean = false;

  // PrimeNG Data Table so that parent component can dynamically set other properties of the data table
  @ViewChild(DataTable) dataTable: DataTable;

  @ContentChild(TemplateRef) rowTemplate: TemplateRef<ElementRef>;
}
Usage - Custom Template

Code: Select all

<dt-wrapper #myDataTable [data]="data" [columns]="columns" [expandableRows]="true">
    <ng-template let-rowData>
        {{ rowData | json }}
    </ng-template>
</dt-wrapper>
Usage - Passing a component

Code: Select all

<dt-wrapper #myDataTable [data]="data" [columns]="columns" [expandableRows]="true">
    <ng-template let-rowData>
        <dt-wrapper #anotherDataTable [data]="rowData.data" [columns]="otherDatatableColumns">
    </ng-template>
</dt-wrapper>
Both examples work as expected, the template passed in the ng-template is then displayed in whichever row is expanded. My question is whether in the case of passing a component in the ng-template, it is possible to get a reference of the child component in the expanded row (anotherDatatable in this case).

I know that ViewChild can be used to get a reference of a component, but I'm not sure if I can read a reference of a component in the expanded row from the parent component. (Of course the component in the expanded row could be any component, I'm just passing another data table as an example here).

I've created this plunker to showcase a simple example of what I'm doing. (https://plnkr.co/edit/5swUtFokLZOfHx8BhwNS?p=preview)

Post Reply

Return to “PrimeNG”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 18 guests