Angular + Material - How to add custom columns in a table (Mat-Table)
What you are trying to achieve is also made in this package angular4-material-table, which add some structure to allow row insertion, edition and deletion. You have an example to add custom actions columns on this plunkr.
You can define a column with your desired buttons/actions:
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="column1">
<mat-header-cell *matHeaderCellDef> column 1 title </mat-header-cell>
<mat-cell *matCellDef="let row">
<!-- col 1 -->
</mat-cell>
</ng-container>
<ng-container matColumnDef="column2">
<mat-header-cell *matHeaderCellDef> column 2 title </mat-header-cell>
<mat-cell *matCellDef="let row">
<!-- col 2 -->
</mat-cell>
</ng-container>
<ng-container matColumnDef="actionsColumn">
<mat-header-cell *matHeaderCellDef>
<button (click)="createNew()">Create new</button>
</mat-header-cell>
<mat-cell *matCellDef="let row">
<button (click)="edit()">Edit</button>
<button (click)="cancelOrDelete()">Cancel</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns">
</mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;">
</mat-row>
</mat-table>
You must include the column in the displayedColumns string array:
displayedColumns = ['column1', 'column2', 'actionsColumn'];
Here is the one way to do it. It might help someone down the road.
table.html
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef>
<ng-container *ngTemplateOutlet="templateRef"></ng-container>
</td>
</ng-container>
table.component
@Input() templateRef: TemplateRef<any>;
table-parent.html
<app-data-table [dataSource]="dataSource" [templateRef]="template">
<ng-template #template>
<button mat-icon-button color="warn">
<mat-icon>delete</mat-icon>
</button>
<button mat-icon-button color="primary">
<mat-icon>edit</mat-icon>
</button>
</ng-template>
</app-data-table>
Hope that saves someone couple hours of search :)
On your TableBasicExample.ts add
export class TableBasicExample {
displayedColumns = ['position', 'name', 'weight', 'symbol', 'customColumn1'];
dataSource = new ExampleDataSource();
}
And in your html file add the column:
<ng-container matColumnDef="customColumn1">
<mat-header-cell *matHeaderCellDef> Custom Title</mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
</ng-container>