0

Given this columns array in a parent component:

columns = [
      { field: 'field1', title: 'Title 1', width: '100px' },
      { field: 'field2', title: 'Title 2', width: '200px' },
      { field: 'field3', title: 'Title 3' }
  ];

I can build a Kendo for Angular grid dynamically in a my-table component:

@Component({
  selector: 'my-table',
  template: `
          <kendo-grid #grid="kendoGrid" [data]="data">
              <kendo-grid-column
                  *ngFor="let column of columns"
                     field="{{column.field}}"
                     title="{{column.title}}"
                     width="{{column.width}}"
              </kendo-grid-column>
          </kendo-grid>
`
})
export class MyTableComponent {
     @Input() data: any[] = [];
     @Input() columns: any[] = [];
}

What I need is to programmatically add to the table a column that contains a button, where the button should execute a function in the parent component.

This is an example of the markup that should be rendered by MyTableComponent:

 <kendo-grid-column>
      <ng-template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">
           <button kendoButton (click)="edit(dataItem,rowIndex)" [icon]="'edit'"></button>
       </ng-template>
 </kendo-grid-column>

MyTableComponent should receive from its parent the information in the columns array, something like this:

columns: [ { isButton: true, buttonLabel: 'Edit', callbackFunc: parentFunc } ];

Can a template be generated programmatically in the table component?

ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

2

The scenario seems possible. You should add a cell template inside the column and use ngIf to render it only for button columns:

<ng-template *ngIf="column.isButton" kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">
    <button kendoButton (click)="column.callbackFunc(dataItem,rowIndex)" [icon]="column.icon">{{ column.buttonLabel }}</button>
</ng-template>

https://stackblitz.com/edit/angular-bzuy99?file=app/app.component.ts

SiliconSoul
  • 799
  • 4
  • 6
  • Can you think of a way to code the button dynamically in the parent without having a prepared markup in the component? Sometimes I have two or three buttons in a single column. – ps0604 Aug 17 '18 at 17:22
  • Should be possible to pass a TemplateRef and render it in the column cell template with ngTemplateOutlet: https://stackblitz.com/edit/angular-bzuy99-qznc1m?file=app/app.component.ts – SiliconSoul Aug 17 '18 at 17:35