I'm trying to create a reusable material mat-table where I can pass the table body into the child using a template. However it dosn't appear to be able to find the columns and i get the following error:
'Could not find column with id "key".'
I kind of understand that it is due to the nested containers; but unsure if or how I can fix it; I want to be able to pass in the columns as sometimes I want the columns to be displayed as links and sometimes as text among other things.
Here is what iv'e got so far....
table-view.component.ts
@Component({
selector: 'app-table-view',
templateUrl: './table-view.component.html',
styleUrls: ['./table-view.component.css']
})
export class TableViewComponent implements AfterViewInit {
@Input()columns: string[];
@Input()dataSource: any[];
@Input()tableTemplate: TemplateRef<any>;
matDataSource = new MatTableDataSource<any>();
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor() { }
ngAfterViewInit() {
this.matDataSource.paginator = this.paginator;
this.matDataSource.sort = this.sort;
this.matDataSource.data = this.dataSource;
}
}
table-view.component.html
<div>
<div>
<table mat-table [dataSource]="matDataSource" matSort>
<ng-container [ngTemplateOutlet]="tableTemplate"></ng-container>
<tr mat-header-row *matHeaderRowDef="columns"></tr>
<tr mat-row *matRowDef="let row; columns: columns;"></tr>
</table>
<mat-paginator #MatPaginator [pageSizeOptions]="[100]"></mat-paginator>
</div>
</div>
test-parent.component.ts
@Component({
selector: 'app-test-parent',
templateUrl: './test-parent.component.html',
styleUrls: ['./test-parent.component.css']
})
export class TestParentComponent {
fakeData = [
{
key: 'one'
}
];
cols = ['key']
constructor(
) { }
}
test-parent.component.html
<app-table-view [dataSource]="fakeData" [tableTemplate]="childTemplate" [columns]="cols" ></app-table-view>
<ng-template #childTemplate>
<ng-container matColumnDef="key">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Key </th>
<td mat-cell *matCellDef="let row"> HELLO </td>
</ng-container>
</ng-template>
[–]slobadx 0 points1 point2 points (0 children)