Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scroll event on angular material 2 autocomplete list using CdkScrollable

I'm trying to use cdkScrollable to listenScrollEvent on mat-autocomplete.

I have implemented like below code snippets.

<mat-form-field>
  <input matInput placeholder="Notebook Page" formControlName="notebookPage" [matAutocomplete]="NBPageAutocomplete" >
</mat-form-field>
<mat-autocomplete  #NBPageAutocomplete="matAutocomplete" cdkScrollable >
  <mat-option  *ngFor="let option of suggestedNBPageNames" [value]="option">
                {{ option }}
  </mat-option>
</mat-autocomplete>

constructor(public scroll: ScrollDispatcher) {}
ngAfterViewInit() {
    this.scroll.scrolled().subscribe((data: CdkScrollable) => {
       console.log(data);
      //make an HTTP call when it reaches to the end, to add some more data
    });
  }

The event was not firing after subscribing to this.scroll.scrolled().

I have been struct on this issue from past few days, didn't find any related info online.

Please help me.

like image 605
Krishna Avatar asked Jul 13 '18 20:07

Krishna


1 Answers

As mentioned in the angular material library, in order to avoid continuous change detection for scroll event, the "scrolled" events emitted will be run outside angular zone by default. For change detection to work, add ngZone.run as below. Please modify the callback in ngZone.run as required.

constructor(public scroll: ScrollDispatcher, private ngZone: NgZone) {}
ngAfterViewInit() {
    this.scroll.scrolled().subscribe((data: CdkScrollable) => {
       console.log(data);
      //make an HTTP call when it reaches to the end, to add some more data
    });
    ngZone.run(() => {
       console.log('to run change detection');
    })
  }
like image 194
adhs91 Avatar answered Sep 22 '22 07:09

adhs91