如何在角度材料垫选择中使用滚动事件? [英] how to use scroll event in angular material mat select?

查看:68
本文介绍了如何在角度材料垫选择中使用滚动事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的列表,我想加载它,因为用户向下滚动选择字段,但我怎么能在mat-select中获得滚动事件,没有事件触发滚动事件。

i have a large list and i want to load it as the user scroll down the select field but how can i get the scroll event in mat-select there is no event that fire the scroll event.

<mat-form-field>
  <mat-select placeholder="Choose a Doctor" formControlName="selectedDoc" (change)="drSelected()">
    <div *ngFor="let dr of doctors;let i = index" [matTooltip]="getDocDetail(i)" matTooltipPosition="right">
      <mat-option (scroll)="docScroll()" [value]="dr">
        {{dr.name}}
      </mat-option>
    </div>
  </mat-select>
  <mat-hint>List Of Doctor In Your city</mat-hint>
  <mat-error *ngIf="selectedDoc.hasError('required')">Please Select A Dr</mat-error>
</mat-form-field>

(滚动)不起作用,因为mat-select没有任何其他方式的滚动事件我可以实现这一点,我希望首先显示10项,然后在用户滚动选项结束时填充剩余项目。

(scroll) don't work because mat-select don't have any scroll event any other way i can achieve this i want to show like 10 item first then populate the rest item when user scroll end of the options .

推荐答案

查看 Stackblitz 我创建了。

在您的组件中,通过 ViewChild获取 MatSelect 访问其可滚动面板。然后向面板添加一个事件监听器,当 scrollTop 位置超过a时,会重新加载医生并更新 viewDoctors 数组一定的门槛。

In your component, get the MatSelect via ViewChild to access its scrollable panel. Then add an event listener to the panel, which reloads the doctors and updated the viewDoctors array when the scrollTop position exceeds a certain threshold.

allDoctors = ['doctor', 'doctor', ..., 'doctor'];
viewDoctors = this.allDoctors.slice(0, 10);

private readonly RELOAD_TOP_SCROLL_POSITION = 100;
@ViewChild('doctorSelect') selectElem: MatSelect;

ngOnInit() {
  this.selectElem.onOpen.subscribe(() => this.registerPanelScrollEvent());
}

registerPanelScrollEvent() {
  const panel = this.selectElem.panel.nativeElement;
  panel.addEventListener('scroll', event => this.loadAllOnScroll(event));
}

loadAllOnScroll(event) {
  if (event.target.scrollTop > this.RELOAD_TOP_SCROLL_POSITION) {
    this.viewDoctors = this.allDoctors;
  }
}

不要忘记分配 mat-select 到模板中的变量,以便您可以通过 ViewChild 访问它:

Don't forget to assign your mat-select to a variable in your template so that you can access it via ViewChild:

<mat-form-field>
  <mat-select placeholder="Choose a Doctor" #doctorSelect>
                                            ^^^^^^^^^^^^^ 
    <mat-option *ngFor="let dr of viewDoctors;let i = index">
      {{dr}}
    </mat-option>
  </mat-select>
</mat-form-field>

这只是说明这个想法的一个非常基本的设置。您可能想要显示加载动画,清理事件监听器,...

This is only a very basic setup illustrating the idea. You might want to do show a loading animation, cleanup the event listener,...

这篇关于如何在角度材料垫选择中使用滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆