San*_*alp 5 angular-material angular
我正在尝试遵循此处给出的 Angular 材料表 - https://material.angular.io/components/table/overview
我正在使用ngFor在displayedColumns. 所以对列名进行硬编码对我来说不是一个选择。
虽然我了解如何displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];选择要显示的列,但如何在呈现表格时更改显示名称?我的表格中的一些名称很长,并且弄乱了表格渲染。
只需使用必要的数据创建一个定义,然后循环这些。我为你创建了一个 stackblitz:https ://stackblitz.com/edit/angular-ykrghm
以下是重要部分:
<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>
Run Code Online (Sandbox Code Playgroud)
——
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'
},
]
Run Code Online (Sandbox Code Playgroud)
我解决了同样的问题
<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>
Run Code Online (Sandbox Code Playgroud)
并且在组件中
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);
}
Run Code Online (Sandbox Code Playgroud)
此处,作为输入传递给组件的 dataSource 是具有 displayColumns 的所有键的对象数组。IE,
export interface SignalCount{
range:string;
lowRange:number;
highRange:number;
populationSize:number;
populationPerc:number;
}
Run Code Online (Sandbox Code Playgroud)
正如您在发布的链接的第一个示例中所看到的,您可以在模板中轻松设置显示的标题名称(此处该列的显示标题名称position将为No.):
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5454 次 |
| 最近记录: |