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

Angular Material 15中mat-paginator默认滚动到顶部如何解决?

解决Angular Material 15中mat-paginator点击分页按钮页面滚动到顶部的问题

这个问题的核心是mat-paginator的上一页/下一页按钮默认是带href="#"的<a>标签,点击时会触发锚点跳转行为,导致页面滚动到顶部。stopPropagation()无效是因为你需要阻止的是默认行为而非事件冒泡。

以下是两种可行的解决方法:

方法一:通过ViewChild监听分页按钮并阻止默认行为

在组件代码中获取mat-paginator实例,找到内部的导航按钮并绑定点击事件阻止默认跳转:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';

@Component({
  selector: 'your-component-selector',
  templateUrl: './your-component.component.html'
})
export class YourComponent implements AfterViewInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  pageSize = 10;
  pageSizeOptions = [5, 10, 20];
  dataSource = /* 你的数据源 */;

  ngAfterViewInit(): void {
    // 获取分页器的上一页/下一页按钮
    const navButtons = this.paginator._elementRef.nativeElement.querySelectorAll(
      '.mat-paginator-navigation-previous, .mat-paginator-navigation-next'
    );
    
    navButtons.forEach((button: HTMLElement) => {
      button.addEventListener('click', (e) => {
        e.preventDefault(); // 阻止锚点跳转的默认行为
      });
    });
  }

  onPaginateChange(): void {
    // 你的分页逻辑
  }
}

方法二:通过事件委托在模板层处理

直接在mat-paginator上绑定点击事件,通过事件委托判断点击目标并阻止默认行为:

模板代码:

<mat-paginator
    *ngIf="dataSource.length > 0"
    [length]="dataSource.length - 1"
    [pageSize]="pageSize"
    [pageSizeOptions]="pageSizeOptions"
    (page)="onPaginateChange()"
    (click)="handlePaginatorClick($event)">
</mat-paginator>

组件代码:

handlePaginatorClick(event: MouseEvent): void {
  const target = event.target as HTMLElement;
  // 验证点击的是分页导航按钮
  if (target.closest('.mat-paginator-navigation-previous') || target.closest('.mat-paginator-navigation-next')) {
    event.preventDefault();
  }
}

注意:如果你的分页逻辑onPaginateChange()中存在数据更新后触发滚动的代码,也需要检查并移除相关逻辑。

内容的提问来源于stack exchange,提问作者rami-sf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:05:32