一般来说,您定义了基于数组的列,例如:
<ng-container *ngFor="let column of tableColumns;let first=first">
<ng-container [matColumnDef]="column.dataKey">
<th [style.width]="column.width" mat-header-cell *matHeaderCellDef>
{{column.name}}
</th>
<td [style.width]="column.width" mat-cell
*matCellDef="let element"> {{element[column.dataKey]}}
</td>
</ng-container>
</ng-container>
而您的显示列为
this.displayedColumns=this.tableColumns.map(x=>x.dataKey)
注意:如果只使用可以使用的数字,我假设您将宽度定义为“50%”或“30px”,例如
[style.width]="column.width+'px'"
更新假设您想创建一个带有操作按钮的列,但这些按钮可以是一个、两个或三个。我们可以为最后一列分配“1%”的宽度和“white-space: nowrap”
//we has two variables
btDelete:boolean=true;
btEdit:boolean:true;
<ng-container matColumnDef="action">
<th style="width:1%" mat-header-cell *matHeaderCellDef>
</th>
<td style="width:1%;white-space: nowrap;" mat-cell
*matCellDef="let element">
<button *ngIf="btEdit" mat-button (click)="edit(element)">Edit</button>
<button *ngIf="btDelete" mat-button (click)="delete(element)">Delete</button>
</td>
</ng-container>
注意:我不太确定列的宽度会发生什么,因为总百分比大于 100%
我们可以尝试在弹性模式下使用 mat-table
<ng-container *ngFor="let column of columns">
<ng-container [matColumnDef]="column.name">
<mat-header-cell [style.flex]="column.width" *matHeaderCellDef> {{column.width}}</mat-header-cell>
<mat-cell [style.flex]="column.width" *matCellDef="let element"> {{element[column.name]}} </mat-cell>
</ng-container>
</ng-container>
<ng-container matColumnDef="action">
<mat-header-cell style="flex:0 1 auto;visibility:hidden" *matHeaderCellDef>
<button *ngIf="btEdit" mat-button>Delete</button>
<button *ngIf="btDelete" mat-button>Delete</button>
</mat-header-cell>
<mat-cell style="flex:0 1 auto" *matCellDef="let element"> <button *ngIf="btEdit" mat-button>Edit</button>
<button *ngIf="btDelete" mat-button>Delete</button></mat-cell>
</ng-container>
看到“动作”列“头部”重复按钮 - 可见性:隐藏 -
注意:在这种情况下,“with”(实际上是 flex-)是一个数字,而不是 %,