Search code examples
angularinfinite-scroll

ngx-infinite-scroll scrolled event won't stop firing


I implemented infinite scroll with ngx-infinite-scroll. When the user reaches the bottom of the scrollable element (with a fixed height), the event 'scrolled' will trigger and call an API to load more items into this element.

The problem is, when I display more data, the scroll level is automatically changed and the event will trigger again. I just want this event to be manually triggered by the user. Is there a way to block to scroll level when I load more data?

   <div
        class="project-feed-container"
        infiniteScroll
        [infiniteScrollDistance]="2"
        [infiniteScrollThrottle]="50"
        [alwaysCallback]="true"
        [scrollWindow]="false"
        (scrolled)="onScroll()"
    >

       <!-- *ngFor with content -->

    </div>

Solution

  • Here's a possible solution to the API response triggering new requests. It is based on a couple of flags that check wether the application can perform new requests.

    canLoad. It controls wether the application can load new items from API.

    pendingLoad. Keeps a queued action that will get triggered on the next polling iteration.

    // NgOnInit to set a time interval to check status. Adjust timing to your need. 
    ngOnInit() {
      setInterval( () => {
        this.canLoad = true;
        if ( this.pendingLoad ) {
          this.onScrollDown();
        }
      }, 2000);
    }
    

    Then, when the scroll functions gets triggered the app should check if it's allowed to call the API and add new elements.

    onScrollDown() {
        if ( this.canLoad ) {
          this.canLoad = false;
          this.pendingLoad = false;
    
          // Call API here
          this.appendItems(0, apiData);
        } else {
          this.pendingLoad = true;
        }
      }
    

    Here's a StackBlitz link with a demo.