Angular CLI 7项目中Angular Material分页、排序、筛选功能失效求助
我帮你排查了代码里的几个关键问题,这些应该就是导致功能失效的核心原因,咱们一个个来修正:
1. 表格数据源绑定错误(最关键)
你的mat-table在模板里绑定的是原始数组projectsGL,但Angular Material的分页、排序、筛选功能是依赖MatTableDataSource实例来工作的,必须把数据源绑定到你组件里定义的dataSource变量:
修改dashboard.component.html里的mat-table标签:
<mat-table #table [dataSource]="dataSource" matSort>
2. AppModule定义错误
你提供的app.module.ts代码明显写错了——你把根模块的类名写成了MaterialModule,这会导致Angular无法正确识别根模块。而且你已经单独创建了material.module.ts来统一导入Material组件,根模块只需要导入这个自定义的MaterialModule即可,不需要重复导入所有Material模块。
修正后的app.module.ts应该是这样:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // Material组件依赖动画模块,必须导入 import { MaterialModule } from './material.module'; // 导入自定义的Material模块 import { AppComponent } from './app.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { ProjectService } from './services/project.service'; // 确保导入你的项目服务 @NgModule({ declarations: [ AppComponent, DashboardComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MaterialModule ], providers: [ProjectService], bootstrap: [AppComponent] }) export class AppModule { }
3. 分页器缺少模板引用变量
你的mat-paginator没有添加模板引用变量,导致组件里的@ViewChild(MatPaginator)无法正确获取到分页器实例。需要给分页器加上#paginator:
修改dashboard.component.html里的分页器标签:
<mat-paginator #paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
4. 调整ViewChild的初始化时机(可选但推荐)
在Angular 7中,@ViewChild默认是static: false,意味着它会在视图初始化完成后(ngAfterViewInit钩子)才会被赋值。你现在在ngOnInit里设置dataSource.paginator = this.paginator,有可能此时分页器还没初始化完成,导致赋值失败。
可以把设置分页器和排序的代码移到ngAfterViewInit:
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core'; // ... 其他导入保持不变 export class DashboardComponent implements OnInit, AfterViewInit { // ... 其他变量保持不变 ngOnInit() { this._projectService.getProjects().subscribe(data => { this.projectsResponse = data; this.initializeProjects(); this.dataSource = new MatTableDataSource<Project>(this.projectsGL); }); } ngAfterViewInit() { // 视图初始化完成后,再绑定分页器和排序 this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } // ... applyFilter和其他方法保持不变 }
做完这些修改后,你的分页、排序、筛选功能应该就能正常工作了。另外要确保你已经安装了@angular/animations依赖,这是Material组件正常运行的必要条件。
内容的提问来源于stack exchange,提问作者Umair Khan

