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

在mat-autocomplete中使用ngx-infinite-scroll时scrolled事件未触发怎么办?

解决mat-autocomplete中ngx-infinite-scroll不触发scrolled事件的问题

问题核心在于mat-autocomplete的滚动容器并非<mat-autocomplete>标签本身,而是它内部动态生成的.mat-autocomplete-panel元素。ngx-infinite-scroll默认监听宿主元素的滚动事件,因此无法捕获到面板的滚动行为。

修改方案:

  1. 在<mat-autocomplete>标签上添加[infiniteScrollContainer]属性,指定实际的滚动容器选择器:
<input type="text" matInput [matAutocomplete]="auto1"/>
<mat-autocomplete
  #auto1="matAutocomplete"
  [class]="'blue-bg'"
  infiniteScroll
  [infiniteScrollDistance]="2"
  [infiniteScrollUpDistance]="15"
  [infiniteScrollContainer]="'.mat-autocomplete-panel'"
  (scrolled)="onScroll()">
  <mat-option *ngFor="let option of simpleOptions.slice(0, currentLimit)" [value]="option">
    {{ option }}
  </mat-option>
</mat-autocomplete>
  1. 调整组件逻辑,实现加载更多的功能:
import { Component } from '@angular/core';

@Component({
  selector: 'app-autocomplete-display-example',
  templateUrl: './autocomplete-display-example.html',
  styleUrls: ['./autocomplete-display-example.css']
})
export class AutocompleteDisplayExample {
  simpleOptions = Array.from({length: 100}, (_, i) => `Option ${i + 1}`);
  currentLimit = 30;

  onScroll() {
    console.log('load more data');
    // 逐步增加显示的选项数量,模拟加载更多逻辑
    if (this.currentLimit < this.simpleOptions.length) {
      this.currentLimit += 20;
    }
  }
}

补充优化:

如果面板动态渲染导致滚动容器初始化延迟,可以监听mat-autocomplete的opened事件,确保容器存在后再触发滚动检查:

<mat-autocomplete
  #auto1="matAutocomplete"
  [class]="'blue-bg'"
  infiniteScroll
  [infiniteScrollDistance]="2"
  [infiniteScrollUpDistance]="15"
  [infiniteScrollContainer]="'.mat-autocomplete-panel'"
  (scrolled)="onScroll()"
  (opened)="onPanelOpened()">
  <!-- 选项内容 -->
</mat-autocomplete>

组件中添加对应方法:

import { Component, ViewChild } from '@angular/core';
import { MatAutocomplete } from '@angular/material/autocomplete';

// ...其他代码

@ViewChild('auto1') auto1!: MatAutocomplete;

onPanelOpened() {
  // 可选:手动触发一次滚动检查,避免初始状态下未满足滚动条件的情况
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:13:14