Angular 8中Mat Paginator的pageSizeOptions不生效问题求助
解决Angular 8中Mat Pagination的pageSizeOptions不生效问题
看起来你的分页核心功能(上/下页)正常,但每页条数的下拉选择器失效且点击报错,这大概率是因为缺少了MatSelectModule的导入——Angular Material分页组件里的页数选择下拉框依赖MatSelect组件,没导入的话会导致下拉无法渲染,进而触发控制台错误。
下面是具体的修复步骤:
1. 在模块文件中补充必要的Material模块
找到你的组件所属的模块(比如AppModule或对应的功能模块SampleViewModule),确保同时导入MatPaginatorModule和MatSelectModule,另外BrowserAnimationsModule是Material组件正常工作的必要前提,也要确认它已被导入:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // 导入Material相关模块 import { MatPaginatorModule } from '@angular/material/paginator'; import { MatSelectModule } from '@angular/material/select'; import { MatTableModule } from '@angular/material/table'; import { MatSortModule } from '@angular/material/sort'; import { MatIconModule } from '@angular/material/icon'; import { SampleViewComponent } from './sample-view.component'; @NgModule({ declarations: [SampleViewComponent], imports: [ BrowserModule, BrowserAnimationsModule, MatTableModule, MatPaginatorModule, MatSortModule, MatIconModule, MatSelectModule // 关键:添加这个模块以支持下拉选择器 ], exports: [SampleViewComponent] }) export class SampleViewModule { }
2. 优化组件内的分页绑定逻辑
你的组件里用了setTimeout来绑定分页器,其实可以去掉这个延迟——Angular 8中@ViewChild的static: true已经确保在组件初始化时能拿到paginator实例,直接同步绑定即可:
display_pattern(){ this.fs.display_pattern(this.pattern).subscribe( (data) => { this.pattern = data.results; this.dataSource = new MatTableDataSource(this.pattern); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; // 移除setTimeout,直接绑定 console.log("Datasource:",this.dataSource) }, err => { console.error(err); } ); }
3. 优化模板中的分页长度配置
模板里的[length]最好动态匹配实际数据总数,而不是写死50,这样分页逻辑会更准确:
<mat-paginator #paginator [pageSizeOptions]="[5, 10, 25, 100]" [length]="dataSource?.data?.length || 0" <!-- 动态获取数据总条数 --> [pageSize]="5" showFirstLastButtons> </mat-paginator>
完成以上步骤后,重启项目,分页的下拉选择器应该就能正常显示和工作了。
内容的提问来源于stack exchange,提问作者Anjana
相关产品推荐
相关产品推荐

