Angular Material 8表格排序功能失效问题求助
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
MatSortModuleinapp.module.ts - You've added the
mat-sort-headerdirective 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

