Search code examples
angularangular-componentsngx-datatableng-templateangular-dynamic-components

How to deal with nested ng-template in Angular


I am making a ngx-datatabel wraper and i want to pass the column template from the parent component. Which i am doing through ng-template outlet. But its not being rendered for some reason.

Here is how i am passing tempalate in parent

<app-list>
  <ng-template #customColumns>
    <ngx-datatable-column name="age" >
      <ng-template let-value="value" ngx-datatable-cell-template>
        Test
      </ng-template>
    </ngx-datatable-column>
  </ng-template>
</app-list>

Here is the child component html

<ngx-datatable [rows]="rows" [columns]="cols">

  <ng-container [ngTemplateOutlet]="customColumnsTemplate">
  </ng-container>

</ngx-datatable>

child component ts

@ContentChild('customColumns')
  customColumnsTemplate: TemplateRef<any>;

If i just copy paste the template directly in child component it works fine but its not working with ngTemplateOutlet.

Currently using Angular 10.1.6


Solution

  • Create an array of columns which contain your templates. It can be an array of objects like so:

    let columns = [{ name: "Column Name", cellTemplate: someCellTemplate, headerTemplate: someHeaderTemplate...}]
    

    Template in this case would be the template in your app-list component.

     <ng-template #myCellTemplate let-row="row" let-column="column" let-value="value">
        Test
     </ng-template>
    

    You access your template in the app-list component with ViewChild

    @ViewChild('myCellTemplate') myCellTemplate: TemplateRef<any>;
    

    Your child component is actually the ngx-datatable wrapper if I understood corectly, so you would only need to send the columns as an input to that wrapper.

    <ngx-datatable [rows]="rows" [columns]="columns">
    </ngx-datatable>
    

    Example from their demos here Ngx-datatable Examples

    Documentation here Doc