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

Angular Material自定义分页显示异常求助

Angular Material自定义分页显示异常修复方案

问题场景

自定义Angular Material分页时,显示逻辑不符合预期:

  • 总页数为4时,当前仅渲染1 2 ...,期望显示1 2 ... 4
  • 总页数大于5时,期望显示1 2 ... [倒数第二页] [最后一页](如总页数5时显示1 2 ... 4 5)
  • 总页数为3时显示1 2 3,该场景正常

问题根源

当前实现的buildPageNumbers方法仅处理了中间范围页码按钮和省略号的渲染,未添加最后一页按钮的逻辑,且省略号的渲染条件未限制重复添加。

修复方案

修改StylePaginatorDirective中的buildPageNumbers方法,补充最后一页按钮的渲染逻辑,并优化省略号的显示条件:

private buildPageNumbers() {
  const actionContainer = this.vr.element.nativeElement.querySelector(
    'div.mat-paginator-range-actions'
  );
  const nextPageNode = this.vr.element.nativeElement.querySelector(
    'button.mat-paginator-navigation-next'
  );

  // 移除旧按钮
  if (this._buttons.length > 0) {
    this._buttons.forEach((button) => {
      this.ren.removeChild(actionContainer, button);
    });
    this._buttons.length = 0;
  }

  // 初始化导航按钮样式(保留原有逻辑)
  let nodeArray = 
    this.vr.element.nativeElement.childNodes[0].childNodes[0].childNodes[2]
      .childNodes;
  setTimeout(() => {
    for (let i = 0; i < nodeArray.length; i++) {
      if (nodeArray[i].nodeName === 'BUTTON') {
        if (nodeArray[i].innerHTML.length > 100 && nodeArray[i].disabled) {
          this.ren.setStyle(
            nodeArray[i],
            'background-color',
            'rgba(190, 130, 130, 1)'
          );
          this.ren.setStyle(nodeArray[i], 'color', 'white');
          this.ren.setStyle(nodeArray[i], 'margin', '.5%');
        } else if (
          nodeArray[i].innerHTML.length > 100 &&
          !nodeArray[i].disabled
        ) {
          this.ren.setStyle(
            nodeArray[i],
            'background-color',
            'rgba(255, 0, 0, 1)'
          );
          this.ren.setStyle(nodeArray[i], 'color', 'white');
          this.ren.setStyle(nodeArray[i], 'margin', '.5%');
        } else if (nodeArray[i].disabled) {
          this.ren.setStyle(nodeArray[i], 'background-color', 'lightgray');
        }
      }
    }
  });

  // 渲染中间范围的页码按钮
  for (let i = 0; i < this.numOfPages; i++) {
    if (i >= this._rangeStart && i <= this._rangeEnd) {
      this.ren.insertBefore(
        actionContainer,
        this.createButton(i, this.matPag.pageIndex),
        nextPageNode
      );
    }
  }

  // 仅当范围结束页小于最后一页时,渲染省略号和最后一页按钮
  if (this._rangeEnd < this.lastPageIndex) {
    // 添加省略号
    this.ren.insertBefore(
      actionContainer,
      this.createButton(this._pageGapTxt, this._rangeEnd),
      nextPageNode
    );
    // 添加最后一页按钮
    this.ren.insertBefore(
      actionContainer,
      this.createButton(this.lastPageIndex, this.matPag.pageIndex),
      nextPageNode
    );
  }
}

修复后验证

  • 总页数为3:渲染1 2 3(符合预期)
  • 总页数为4:渲染1 2 ... 4(符合预期)
  • 总页数为5:渲染1 2 ... 4 5(符合预期)
  • 总页数大于5:渲染1 2 ... [倒数第二页] [最后一页](符合预期)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:07:34