I'm trying to follow the Angular material table given here- https://material.angular.io/components/table/overview
I am using ngFor
to display all available columns in displayedColumns
. So hardcoding the column names isn't an option for me.
While I understand how displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
is there to choose which columns to display, how can I change the display name when the table is rendered? Some of the names in my table are lengthy and are messing up the table render.
Just create a definition with the necessary data, and loop these. I created a stackblitz for you: https://stackblitz.com/edit/angular-ykrghm
Here are the important parts:
<ng-container *ngFor="let def of tableDef">
<ng-container [matColumnDef]="def.key">
<th mat-header-cell *matHeaderCellDef> {{def.header}} </th>
<td [ngClass]="def.className" mat-cell *matCellDef="let element"> {{element[def.key]}} </td>
</ng-container>
--
tableDef: Array<any> = [
{
key: 'position',
header: 'Position',
className: 'something'
}, {
key: 'name',
header: 'Element Name',
className: 'anElement'
}, {
key: 'weight',
header: 'Weight',
className: 'number'
}, {
key: 'symbol',
header: 'A long text to display in header',
className: 'something'
},
]
I solved the same problem as
<table mat-table class="lmat-elevation-z8" [dataSource]="dataSource" matSort matSortActive="Range" matSortDirection="asc" matSortDisableClear>
<ng-container *ngFor="let dispCol of displayedColumns; let colIndex = index" matColumnDef="{{dispCol.key}}">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{dispCol.header}}</th>
<td mat-cell *matCellDef="let element" class="mat-column-vinCode">{{element[dispCol.key]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumnsKeys; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumnsKeys"></tr>
</table>
And in component
export class RawSignalsContainerComponent implements OnInit{
constructor() { }
@Input() dataSource: Array<SignalCount>;
displayedColumns: Array<any>;
displayedColumnsKeys: string[];
ngOnInit() {
displayedColumns= [
{
key: 'range',
header: 'Range'
},
{
key: 'lowRange',
header: 'Low Range'
},
{
key: 'highRange',
header: 'High Range'
},
{
key: 'populationSize',
header: 'Population Size'
},
{
key: 'populationPerc',
header: '% of Population'
}
];
this.displayedColumnsKeys = this.displayedColumns.map(col => col.key);
}
Here, dataSource passed as input to the component is the array of objects with all keys of displayedColumns. i.e.,
export interface SignalCount{
range:string;
lowRange:number;
highRange:number;
populationSize:number;
populationPerc:number;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With