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

Angular使用MatSort实现点击表格表头切换列升降序排序功能问题

实现方案

1. 确认模块导入

首先在你组件所属的模块文件(如app.module.ts或对应功能模块)中,确保已经导入MatSortModule:

import { NgModule } from '@angular/core';
import { MatSortModule } from '@angular/material/sort';
// 其他已导入的依赖如MatTableModule、MatPaginatorModule等保持不变

@NgModule({
  imports: [
    // 原有导入项
    MatSortModule
  ]
})
export class AppModule { }

2. 修正组件TS代码

你现有代码中MatSort的视图查询没有配置static属性,会导致初始化时机错误,调整代码如下:

export class ObjectComponent implements OnInit {
  displayedColumns: string[] = ["id", "name", "vorname", "mobileNumber", "secondMobileNumber", "email", "secondEmail", "roomNumber", "task", "Notes", "Edit", "Delete"];
  dataSource = new MatTableDataSource<ContactListEntry>(FORMULARLIST);

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  // 给MatSort加上static: true配置
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  ngOnInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    // 初始排序状态配置
    const sortState: Sort = { active: 'name', direction: 'desc' };
    this.sort.active = sortState.active;
    this.sort.direction = sortState.direction;
    this.sort.sortChange.emit(sortState);

    // 可选配置:禁止第三次点击清空排序,只在升序/降序之间切换
    // this.sort.disableClear = true;
  }
}

你原有代码中重复给paginator赋值的setTimeout逻辑冗余,可以直接删除。

3. 优化HTML代码(可选)

Edit、Delete属于操作列,不需要排序能力,建议删除这两列表头上的mat-sort-header属性,避免误触发排序:

<ng-container matColumnDef="Delete">
    <!-- 移除mat-sort-header属性 -->
    <th mat-header-cell *matHeaderCellDef>Delete</th>
    <td mat-cell *matCellDef="let formular">
        <button (click)="openDialogDelete(formular.id)" mat-mini-fab color="warn">
            <mat-icon>delete</mat-icon>
        </button>
    </td>
</ng-container>

<ng-container matColumnDef="Edit">
    <!-- 移除mat-sort-header属性 -->
    <th mat-header-cell *matHeaderCellDef>Edit</th>
    <td mat-cell *matCellDef="let formular">
        <button (click)="openDialogEdit(formular)" mat-mini-fab color="black">
            <mat-icon>edit</mat-icon>
        </button>
    </td>
</ng-container>

交互逻辑说明

调整完成后,Angular Material原生的MatSort组件已经自带你需要的交互:

  • 首次点击列头:按该列升序排列
  • 第二次点击同个列头:切换为降序排列
  • 第三次点击同个列头:恢复原始数据顺序(如果开启了上面的disableClear配置则不会触发这一步,只会在升序降序间切换)

内容的提问来源于stack exchange,提问作者max_flu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:54:02