使用 MatTable 时,如何为可排序列动态添加 aria-sort 属性?

解读

国内中高级前端面试常把「无障碍」作为区分“能用”与“专业”的试金石。MatTable 的 mat-sort-header 指令虽然自带键盘交互与样式,但不会自动把当前排序状态同步到 aria-sort,而国内政企、金融、运营商项目普遍要求过国家无障碍三级/二级测评。如果候选人只说“MatSort 已经处理了”,会被直接判为“不了解国内合规要求”。面试官真正想听的是:

  1. 如何不破坏 Material 源码的前提下,把排序状态投射到 DOM;
  2. 如何只改动可排序列,避免全表属性污染;
  3. 如何与 OnPush 变更策略共存,不触发额外脏检查;
  4. 如何在懒加载、动态列、服务端排序场景下依旧生效。

知识点

  • MatSort 的 stateChanges 可观察对象:它在排序字段或方向变化时会发出 Sort 对象,方向值为 asc/desc/''。
  • ARIA 1.2 规范:aria-sort 只有 enum 值「ascending、descending、none、other」,空字符串需映射为 none。
  • 指令的 host 绑定优先级:自定义指令的 @HostBinding('attr.aria-sort') 会覆盖组件默认属性,因此可以把逻辑封装成属性型指令挂在 mat-header-cell 上。
  • ChangeDetectionStrategy.OnPush:直接对指令内部 changeDetectorRef.markForCheck() 即可,无需全局脏检。
  • 动态列场景:列定义数组变化时,指令通过 MatColumnDef 注入令牌拿到当前列名,与 MatSort.active 比对,自动订阅或退订,避免内存泄漏。
  • 服务端排序:只要保证 MatSort 的 (sort) 事件把新状态写回同一份 Sort 实例,stateChanges 依旧会触发,指令无感知。

答案

  1. 新建 sort-a11y.directive.ts:
@Directive({
  selector: '[sortA11y]',
  standalone: true
})
export class SortA11yDirective implements OnDestroy {
  @HostBinding('attr.aria-sort') ariaSort: 'ascending' | 'descending' | 'none' = 'none';

  private destroy$ = new Subject<void>();

  constructor(
    @Optional() private matSort: MatSort,
    @Optional() private columnDef: MatColumnDef
  ) {
    if (!this.matSort || !this.columnDef) { return; }

    this.matSort.stateChanges
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => this.updateAria());
    this.updateAria(); // 初始值
  }

  private updateAria(): void {
    const active = this.matSort.active === this.columnDef.name;
    const direction = active ? this.matSort.direction : '';
    this.ariaSort = direction === 'asc'  ? 'ascending'
                  : direction === 'desc' ? 'descending'
                  : 'none';
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
  1. 模板侧零侵入使用:
<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef mat-sort-header sortA11y>姓名</th>
  ...
</ng-container>
  1. 模块中只需把指令声明为 standalone: true 并在组件 imports 引入即可,无需额外 providers。

至此,可排序列在运行时会被动态写入 aria-sort="ascending|descending|none",非排序列始终保持 none,完全满足国内无障碍测评要求,且与 OnPush、懒加载、动态列、服务端排序无缝兼容。

拓展思考

  • 多列联合排序:Material 默认只支持单列,若业务需要“主序+次序”,可扩展自定义 MatSort 派生类,在 stateChanges 里发出数组,指令端把当前列在数组中的位次拼成 aria-sort="other" 并追加 aria-label 说明排序优先级,评审专家会认可这种渐进增强思路。
  • 性能极限优化:列数 >200 的财务透视表场景,可使用 animationFrameScheduler 把更新批量推到下一帧,避免 200 次同步 DOM 写。
  • 单元测试:利用 MatSortHarness 触发排序后,通过 HarnessEnvironment 拿到原生 <th>,断言 aria-sort 值,国内甲方验收时必须提供测试报告,提前准备可加分。