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