表头固定时如何让mat-progress-bar显示在表格表头下方
解决mat-progress-bar在固定表头下方显示的问题
问题原因
你之前把<mat-progress-bar>放在<th>标签外面,但Angular Material的mat-table会将<ng-container>里的<th>收集到mat-header-row对应的表头行中,不在<th>内的元素不会被纳入表格结构,所以进度条无法显示。同时要让进度条跟着固定表头滚动,必须让它成为表头单元格的一部分。
修复步骤
1. 调整HTML结构,将进度条移入表头单元格内
修改<ng-container>里的表头单元格代码,把进度条放到<th>内部,同时给表头单元格添加类名方便样式控制:
<table (matSortChange)="sortData($event)" mat-table [dataSource]="dataSource" matSort id="table"> <ng-container matColumnDef={{col.matColumnDef}} *ngFor="let col of gridColumns"> <!-- 将进度条移入<th>内部 --> <th mat-header-cell *matHeaderCellDef cdkDrag mat-sort-header class="sticky-header-cell"> <div class="header-title">{{col.columnHeader}}</div> <mat-progress-bar mode="indeterminate" class="header-progress"></mat-progress-bar> </th> <td mat-cell *matCellDef="let row"> <span *ngIf="col.columnHeader !== 'Property Name'"> {{(col.value(row) !== 'null')? col.value(row) : '-'}} </span> <span *ngIf="col.columnHeader === 'Property Name'"> {{(col.value(row) !== 'null')? col.value(row) : '-'}} <br> <span class="property-sub-content">{{row.city}}, {{row.state}}</span> </span> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns;"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="getPlaceDetails(row.propertyAccountId)"></tr> </table>
2. 添加CSS样式,确保布局和固定效果
在组件的样式文件中添加以下样式,让表头单元格垂直排列内容,同时保持sticky固定:
/* 表头单元格:固定在顶部,垂直布局 */ .sticky-header-cell { position: sticky; top: 0; background-color: #ffffff; /* 防止滚动时下方内容穿透 */ display: flex; flex-direction: column; justify-content: center; padding: 0.5rem 0; } /* 表头标题:和进度条拉开间距 */ .header-title { margin-bottom: 0.25rem; } /* 进度条:居中显示,调整宽度避免撑满单元格 */ .header-progress { width: 90%; align-self: center; }
效果说明
- 进度条现在会显示在每个表头标题的下方,符合你想要的位置
- 当表格滚动时,因为进度条属于固定的表头单元格,会跟着表头一起保持在顶部可见
- 样式可以根据你的需求调整内边距、宽度、颜色等参数
内容的提问来源于stack exchange,提问作者Tim Launders
相关产品推荐
相关产品推荐

