Friday 22 February 2019

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

I would like to use virtual scroll on my Angular application. The items in my list are the result of a remote paged search. I would like to load more results (call the next page) every time I reach the end of the viewport scrolling down.

Here is my template:

<div class="container">
    <cdk-virtual-scroll-viewport itemSize="100">
        <li *cdkVirtualFor="let item of searchResult"></li>
    </cdk-virtual-scroll-viewport>
</div>

Here is my attempts to make it to work as I need:

    export class SearchComponent {
        @ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport;
        searchPageNumber: number;
        searchResults: Array<any>;

        constructor(private scrollDispatcher: ScrollDispatcher, private searchService: SearchService) {
            this.searchPageNumber = 0;
            this.searchResults = [];
        }

        ngOnInit(): void {
            this.nextSearchPage(this.searchPageNumber);
        }

        ngAfterViewInit(): void {
            //this.scrollDispatcher.register(this.scrollable);
            //this.scrollDispatcher.scrolled(1000)
            //    .subscribe((viewport: CdkVirtualScrollViewport) => {
            //        console.log('scroll triggered', viewport);
            //    });

            this.virtualScroll.renderedRangeStream.subscribe(range => {
                console.log('range', range);
                console.log('range2', this.virtualScroll.getRenderedRange());
                if (this.virtualScroll.getRenderedRange().end % 10 === 0) {
                    this.nextSearchPage(++this.searchPageNumber);
                }
            });
        }

        nextSearchPage(pageNumber: number): void {
            this.searchService.getResults(pageNumber).then((pagedResults) => {
                this.searchResults = this.searchResults.concat(pageResuls);
            });
        }
    }

As you can see I can't figure out how to trigger the call to my nextSearchPage function (to load more results) only when the scrollbar reaches the end of the current rendered items in the list.

Do you know how can I do that?

Angular scrolling documentation is poor and it lacks of examples, as stated in this issue as well.



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

No comments:

Post a Comment