Angular virtual scroll: append new items when reaching the end of scroll

There is a function measureScrollOffset on CdkScrollable that may help. you can subscribe to scroll events and check the offset to determine where you have scrolled.

  ngAfterViewInit(): void {
    this.scrollDispatcher.scrolled().pipe(
      filter(event => this.virtualScroll.measureScrollOffset('bottom') === 0)
    ).subscribe(event => {
      this.searchPageNumber++;
      this.nextSearchPage(this.searchPageNumber); 
    })

And you need to manually call detectChange after scroll item collection change. There's one problem though I have not find a solution: the scroll bar will return to beginning after change detection.

Check the demo here: https://stackblitz.com/edit/template-angular7-material-primeng-ckxgzs

Edit:

Turns out listening for end of scroll is probably not a good idea. A better one is listening for rendering range(I believe it's the actual items rendered in the DOM) change. Once the rendering range ends equals data length, that's the time to add more data to the collection. And this somehow solves the problem of bar going back to beginning.

 ngAfterViewInit(): void {
    this.scrollDispatcher.scrolled().pipe(
      filter(event => this.virtualScroll.getRenderedRange().end === this.virtualScroll.getDataLength())
    ).subscribe(event => {
      this.searchPageNumber++;
      this.nextSearchPage(this.searchPageNumber);
    })

New demo here: https://stackblitz.com/edit/template-angular7-material-primeng-fhikcf

To be honest, I got the idea from: https://angularfirebase.com/lessons/infinite-virtual-scroll-angular-cdk/ You probably can learn more there.


The easiest way to solve this is with the scrolledIndexChange.

<cdk-virtual-scroll-viewport itemSize="500" (scrolledIndexChange)="nextBatch($event)">

$event is the first index of rendered elements at the moment. Therefore, you can call the next page when the index of the first item is near the end of the items in the list

Remember that the items have a fixed height (itemSize) so it is easy to identify the amount of elements that are rendered at a time.

e.g.

  nextBatch(index) {
    if (index + $itemsRenderAtTheMoment === this.items.length - 1) {
      this.page ++;
      this.loadMore();
    }
  }