使用Angular Material的MatSort时出现编译报错如何解决
问题原因
- 类型不匹配:你声明的
customers为普通any[]数组类型,JavaScript原生数组自带的sort是接收比较函数、返回排序后数组的内置方法,你要赋值的this.sort是Angular Material的MatSort类实例,二者类型完全不兼容,因此触发TS类型报错。 - 用法错误:你参考的教程中是将
MatSort实例绑定给MatTableDataSource实例的sort属性,而非直接赋值给普通数组的内置sort方法,这是写法的核心问题。 - 生命周期时机错误:
@ViewChild查询的MatSort实例在ngOnInit阶段还未完成初始化,即使类型匹配,该阶段赋值也会拿到undefined。
解决方案
按以下步骤修改代码即可正常运行:
- 引入
MatTableDataSource,替换customers的类型定义
首先在文件头部导入依赖:
import { MatTableDataSource } from '@angular/material/table';
替换原有customers变量声明:
// 替换原有 customers!: any[]; 为如下代码 customers!: MatTableDataSource<any>;
- 修改数据赋值逻辑,将接口返回的数组封装为
MatTableDataSource实例
ngOnInit(): void { this.northwindService.apiCustomersGet().subscribe(data => { this.customers = new MatTableDataSource(data); // 数据源初始化完成后绑定排序能力 this.customers.sort = this.sort; }); }
- 补充生命周期实现,确保
MatSort实例正常加载
修改组件类的实现接口,增加AfterViewInit:
export class CustomersComponent implements OnInit, AfterViewInit {
如果需要更稳妥的绑定时机,也可以将sort赋值逻辑移到ngAfterViewInit钩子中:
ngAfterViewInit() { if (this.customers) { this.customers.sort = this.sort; } }
- 确认模板配置正确
模板中mat-table需要绑定matSort指令,示例如下:
<table mat-table [dataSource]="customers" matSort> <!-- 你的列定义代码保持不变 --> </table>
内容的提问来源于stack exchange,提问作者saja
相关产品推荐
相关产品推荐

