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

使用Angular Material的MatSort时出现编译报错如何解决

问题原因
  • 类型不匹配:你声明的customers为普通any[]数组类型,JavaScript原生数组自带的sort是接收比较函数、返回排序后数组的内置方法,你要赋值的this.sort是Angular Material的MatSort类实例,二者类型完全不兼容,因此触发TS类型报错。
  • 用法错误:你参考的教程中是将MatSort实例绑定给MatTableDataSource实例的sort属性,而非直接赋值给普通数组的内置sort方法,这是写法的核心问题。
  • 生命周期时机错误:@ViewChild查询的MatSort实例在ngOnInit阶段还未完成初始化,即使类型匹配,该阶段赋值也会拿到undefined。
解决方案

按以下步骤修改代码即可正常运行:

  1. 引入MatTableDataSource,替换customers的类型定义
    首先在文件头部导入依赖:
import { MatTableDataSource } from '@angular/material/table';

替换原有customers变量声明:

// 替换原有 customers!: any[]; 为如下代码
customers!: MatTableDataSource<any>;
  1. 修改数据赋值逻辑,将接口返回的数组封装为MatTableDataSource实例
ngOnInit(): void {
  this.northwindService.apiCustomersGet().subscribe(data => {
    this.customers = new MatTableDataSource(data);
    // 数据源初始化完成后绑定排序能力
    this.customers.sort = this.sort;
  });
}
  1. 补充生命周期实现,确保MatSort实例正常加载
    修改组件类的实现接口,增加AfterViewInit:
export class CustomersComponent implements OnInit, AfterViewInit {

如果需要更稳妥的绑定时机,也可以将sort赋值逻辑移到ngAfterViewInit钩子中:

ngAfterViewInit() {
  if (this.customers) {
    this.customers.sort = this.sort;
  }
}
  1. 确认模板配置正确
    模板中mat-table需要绑定matSort指令,示例如下:
<table mat-table [dataSource]="customers" matSort>
  <!-- 你的列定义代码保持不变 -->
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:27:02