You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular表格多列固定问题:实现Name、No及最后一列固定

解决方案

要实现Name、No.(Position列)和最后一列的固定效果,需要两步调整:

1. 为第二列添加sticky属性

在HTML中,给position列的ng-container加上sticky属性,标记该列为固定列:

<!-- Position Column -->
<ng-container matColumnDef="position" sticky>
  <th mat-header-cell *matHeaderCellDef> No. </th>
  <td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>

2. 自定义CSS避免固定列重叠

Angular Material默认只会给第一个左侧固定列设置left: 0,多个左侧固定列会出现重叠问题,需要通过CSS为每个固定列设置对应的left偏移量:

.example-container {
  overflow: auto;
  max-width: 100%;
}

/* 第一列固定在最左侧 */
.mat-column-name {
  left: 0;
  z-index: 1;
}

/* 第二列固定在第一列右侧,偏移量匹配第一列宽度 */
.mat-column-position {
  left: 120px; /* 可根据实际列宽调整数值 */
  z-index: 1;
}

修改后的完整代码

HTML部分

<div class="example-container mat-elevation-z8">
  <table mat-table [dataSource]="dataSource">

    <!-- Name Column -->
    <ng-container matColumnDef="name" sticky>
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <!-- Position Column -->
    <ng-container matColumnDef="position" sticky>
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef> Symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>

    <!-- Star Column -->
    <ng-container matColumnDef="star" stickyEnd>
      <th mat-header-cell *matHeaderCellDef></th>
      <td mat-cell *matCellDef="let element">
        <mat-icon>more_vert</mat-icon>
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

CSS部分(table-sticky-columns-example.css)

.example-container {
  overflow: auto;
  max-width: 100%;
}

.mat-column-name {
  left: 0;
  z-index: 1;
  min-width: 120px; /* 可选:设置最小宽度保证列内容不被截断 */
}

.mat-column-position {
  left: 120px;
  z-index: 1;
  min-width: 80px; /* 可选:设置最小宽度 */
}

TS部分无需修改,保持原代码即可。


内容的提问来源于stack exchange,提问作者Mr. Mark Tawin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:53:14