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

Angular Material 8表格排序功能失效问题求助

Angular Material Table Sort Not Working? Here's the Fix

Hey there! Let's figure out why your table sorting isn't kicking in even though the arrows show up and there are no console errors. I spotted the issue in your component code right away.

The Root Cause

In your loadAllEnvironments method, after fetching the environment data, you're creating a new MatTableDataSource instance and assigning it to this.dataSource. While you set the paginator for this new data source, you forgot to bind the MatSort instance to it!

Earlier in ngOnInit, you set this.dataSource.sort = this.sort, but that only applies to the initial empty data source you created at the top of the component. When you replace this.dataSource with a new instance later, that sort binding is lost.

The Solution

You have two clean ways to fix this:

Option 1: Bind the sort when creating the new data source

Update your loadAllEnvironments method to set the sort property right after creating the new data source:

private loadAllEnvironments() {
  this.environmentService.getEnvironmentDetails()
  .subscribe(environments => {
    this.environments = environments;
    this.dataSource = new MatTableDataSource(this.environments);
    this.dataSource.paginator = this.paginator;
    // Add this line to bind the sort to the new data source
    this.dataSource.sort = this.sort;
  });
  return this.environments;
}

Option 2: Avoid creating a new data source (more efficient)

Instead of replacing the entire data source, just update its data property. This way, you keep the initial sort and paginator bindings you set in ngOnInit:

// First, initialize your data source without passing the empty array (optional but cleaner)
dataSource = new MatTableDataSource<Environment>();

// Then update loadAllEnvironments:
private loadAllEnvironments() {
  this.environmentService.getEnvironmentDetails()
  .subscribe(environments => {
    this.environments = environments;
    // Just update the data property instead of creating a new instance
    this.dataSource.data = environments;
    this.dataSource.paginator = this.paginator;
    // No need to set sort here since it's already bound in ngOnInit
  });
  return this.environments;
}

Quick Double-Checks

Just to be thorough, let's confirm you already have these correct (which you do in your code):

  • You've imported MatSortModule in app.module.ts
  • You've added the mat-sort-header directive to your header cells
  • You've used @ViewChild(MatSort) to get a reference to the sort component

Either of the fixes above should get your sorting working properly. Give it a try!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:35