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

如何让MatPaginator始终保持自定义长度?

解决MatPaginator自定义长度搜索后失效问题

问题分析

初始加载时自定义分页长度正常,但搜索后分页器回到dataSource默认长度,核心原因是搜索更新dataSource后,MatTableDataSource会自动将分页器的length重置为当前数据的长度,覆盖了你HTML中绑定的自定义长度值。

解决方案

按以下步骤修改代码,确保自定义长度优先生效:

  1. 修正HTML的length条件绑定
    直接在模板中通过三元表达式判断,优先使用自定义长度,否则 fallback 到dataSource的默认长度:

    <mat-paginator #usersPaginator 
                   [length]="usersService.customizedLength() !== 0 ? usersService.customizedLength() : dataSourceUsers.data.length" 
                   [pageSizeOptions]="[5,10,15]" 
                   [showFirstLastButtons]="true" />
    

    如果是服务器端分页(dataSource中存储的是当前页数据,总条数单独维护),把dataSourceUsers.data.length替换成你的总条数变量(比如dataSourceUsers.totalCount)。

  2. 在dataSource更新后手动同步分页器长度
    搜索API返回新数据后,手动覆盖分页器的length值,避免被MatTableDataSource自动重置:

    // 示例:搜索请求成功后的处理逻辑
    this.userSearchService.searchUsers(searchParams).subscribe({
      next: (response) => {
        this.dataSourceUsers.data = response.data;
        // 同步分页器长度
        if (this.usersPaginator) {
          this.usersPaginator.length = this.usersService.customizedLength() !== 0 
            ? this.usersService.customizedLength() 
            : response.totalCount; // 这里替换成你的默认总条数
        }
      }
    });
    
  3. 调整ViewChild的使用方式(可选但更直观)
    把原有的setter改成直接获取实例,方便后续手动操作:

    @ViewChild('usersPaginator') usersPaginator!: MatPaginator;
    
    ngAfterViewInit() {
      if (this.dataSourceUsers) {
        this.dataSourceUsers.paginator = this.usersPaginator;
      }
    }
    

关键注意点

  • 如果使用服务器端分页,一定要确保customizedLength()信号在每次API请求后都正确更新为新的总条数。
  • 避免依赖MatTableDataSource的自动分页同步,对于自定义逻辑场景,手动控制分页器参数更可靠。

内容的提问来源于stack exchange,提问作者k.vincent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:28:11