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

如何让ngx-infinite-scroll在Angular的mat-tab中正常触发?

解决Angular mat-tab中ngx-infinite-scroll无法触发的问题

问题核心是mat-tab-body-content会自动生成滚动条,而ngx-infinite-scroll默认监听的不是这个容器,导致滚动事件无法被捕获。以下是两种可行的实现方式:

方式一:指定滚动容器并禁用window监听

  1. 修改HTML结构,给带infiniteScroll指令的容器添加固定高度,设置scrollWindow="false",同时通过[infiniteScrollContainer]指定滚动容器为mat-tab-body-content:
<mat-tab-group *ngIf="tabs" (selectedIndexChange)="onTabSelected($event)" [tabIndex]="tabIndex">
    <mat-tab *ngFor="let t of tabs" [label]="t.name">
        <div
            infiniteScroll
            scrollWindow="false"
            [infiniteScrollContainer]="'.mat-tab-body-content'"
            fxLayout="column"
            fxFlex="100"
            style="height: 100%; overflow: auto;"
            (scrolled)="onScroll()">
            <mat-spinner *ngIf="loading"></mat-spinner>
            <div  *ngIf="data"
                fxLayout="row wrap"
                fxLayoutGap="7px"
                class="element-list">
                <app-image-preview  class="selector-element"
                *ngFor="let item of data"
                [fxFlex]="widthProc"
                [container]="item[container]"
                [fileId]="item[image]"
                [variant]="variant"
                [caption]="item[caption]"
                (onSelected)="onImageSelected($event,item)"
                ></app-image-preview>
            </div>
        </div>
    </mat-tab>
</mat-tab-group>
  1. 可选:在全局样式中移除mat-tab-body-content的默认滚动,避免双重滚动:
.mat-tab-body-content {
    overflow: hidden !important;
}

方式二:通过ViewChild获取滚动容器并绑定

如果CSS选择器绑定不稳定,可在组件类中通过ViewChild获取当前激活的tab内容容器:

  1. 组件类添加代码:
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { MatTabGroup } from '@angular/material/tabs';

// ...

@ViewChild(MatTabGroup) tabGroup!: MatTabGroup;
scrollContainer!: ElementRef;

ngAfterViewInit() {
    // 获取初始激活的tab内容容器
    this.scrollContainer = this.tabGroup._elementRef.nativeElement.querySelector('.mat-tab-body-content');
}

onTabSelected(index: number) {
    this.tabIndex = index;
    // 切换tab后延迟获取当前tab的滚动容器(确保DOM已更新)
    setTimeout(() => {
        this.scrollContainer = this.tabGroup._elementRef.nativeElement.querySelector('.mat-tab-body-content');
    });
}
  1. 修改HTML中的infiniteScrollContainer绑定:
<div
    infiniteScroll
    scrollWindow="false"
    [infiniteScrollContainer]="scrollContainer"
    fxLayout="column"
    fxFlex="100"
    style="height: 100%;"
    (scrolled)="onScroll()">

关键注意点

  • 必须设置scrollWindow="false",让指令监听指定容器而非全局window。
  • 滚动容器需要有明确高度(比如100%,需确保父容器也有高度设置),否则无法产生滚动条。
  • 切换tab时需重新绑定滚动容器,因为非激活tab的内容会被隐藏或销毁,DOM元素可能不存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:20:34