INFINITE SCROLL IN IONIC

Share the post

Hello All, In the last topic, We had discussed How to generate QR code in the Ionic 4 application example. Today we will see the most useful concept in the ionic framework called the infinite-scroll component. Suppose, you have 1000 records & you want to display them using the list. This list contains 1000 records so it will require a scroll option. To use the infinite scroll option in Ionic we use the infinite-scroll component.

the ion-infinite-scroll component uses the event function called ionInfinite. When the user reaches a distance that is viewable defined distance then ionInfinite event is called. When this event completes then it will call the complete() method. We will see How to use the ion-infinite-scroll component using an example.

How to use the ion-infinite-scroll component in ionic

1. Generate a new page using Ionic CLI

ionic g page infinite-scroll

2. Copy below HTML to infinite-scroll.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>INFINITE SCROLL EXAMPLE</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  
  <ion-list>
    <ion-item *ngFor="let item of data">
      <ion-label>{{item}}</ion-label>
    </ion-item>
  </ion-list>

  <ion-infinite-scroll threshold="100px" (ionInfinite)="loadData($event)">
    <ion-infinite-scroll-content
      loadingSpinner="bubbles"
      loadingText="Loading data...Please wait">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

3. Copy below ts to infinite-scroll.page.ts

import { Component, ViewChild } from '@angular/core';
import { IonInfiniteScroll } from '@ionic/angular';

@Component({
  selector: 'app-infinite-scroll',
  templateUrl: './infinite-scroll.page.html',
  styleUrls: ['./infinite-scroll.page.scss'],
})
export class InfiniteScrollPage {

  @ViewChild(IonInfiniteScroll, { static: false }) infiniteScroll: IonInfiniteScroll;

  data: any = [];

  constructor() {
    this.data = [];

    for (let i = 0; i < 50; i++) {
      this.data.push("Value of i " + i);
    }
  }

  loadData(event) {

    setTimeout(() => {
      for (let i = 0; i < 50; i++) {
        this.data.push("Value of i " + i);
      }
      event.target.complete();

      if (this.data.length == 100) {
        event.target.disabled = true;
      }
    }, 500);
  }
}

Here, we are displaying the first 50 records to the user. If the user scrolls down to above 50 records then ionInfinite will be called & we are calling the loadData() method from ts. In this method, we set the timeout method to increase our list items. Once the list items reach 100 then the complete() method will call & it disables the scrolling function. In this way, We can able to achieve the scrolling functionality in an Ionic application.

Output

infinite-scroll_output
infinite-scroll output

1 thought on “INFINITE SCROLL IN IONIC”

Leave a Comment