Friday, June 28, 2019

create infinite scroll pagination directive in angular

I the web application if you want to display lots of data then you must have to get data as per required using pagination.

if you have more than 10000 records/data and get all at page load then your app will be stuck/takes too much time to load.

to overcome this problem here, we will discuss how to get Endless Scrolling data means Ajax scroll down pagination using angular.

here, we have used angular 7 for pagination. you can also implement this demo in any versions like angular 2, angular 4, angular 5, angular 6, angular 7, angular 8, etc. and in any template engine or any front-end framework.

Demo: common-scroll-pagination.directive.ts
/*
*Infinite scroll bar directive/ plugin
*/

import { Directive, ElementRef, AfterViewInit, HostListener, Input, Output, EventEmitter } from '@angular/core';
declare const $: any;

@Directive({
  selector: '[appScrollPagination]'
})
export class scrollPaginationDirective implements AfterViewInit {

  @Input() isScroll: boolean= false;
  @Input() scrollTrigger: number = 70;
  @Output() callScrollPaginationMethod = new EventEmitter();

  constructor(private el: ElementRef) { }

  ngAfterViewInit(): void {
  }

  @HostListener("window:scroll", [])
  onWindowScroll() {
    let scrollPercent = Math.round(($(window).scrollTop()) / ($(document).height() - $(window).height()) * 100);
    //console.log("here for scroll from scrollPaginationDirective........ : ", this.isScroll, scrollPercent, this.scrollTrigger);
    if (scrollPercent > this.scrollTrigger) {
      if (this.isScroll === true) {
        this.callScrollPaginationMethod.next();
      }
    }
  }
}

user.components.ts
<div appScrollPagination [isScroll]="postRecordsOffset < postRecordsTotal" (callScrollPaginationMethod)="getUsers({ action: 'viewMore' });">
   
      <div *ngFor="let userData of users; let i = index;">
          -------
          -------
          -------
      </div>
</div>

In the above code

@Input() isScroll is used to determine whether function/ method call on a scroll or not. this is most used when no more data is available.

@Input() scrollTrigger is used to trigger a particular function when the scroll bar is equal or greater than to the this passed value.

@Output() callScrollPaginationMethod = new EventEmitter() is used to trigger function by which can be  call component's method from this directive .

here, if isScroll and scrollTrigger attributes are not passed from html directive then it will take the default value.

I think It's very easy to use this directive code.

For more information check following link

http://laxmanchavda.blogspot.com/2018/06/how-to-create-infinite-scroll-pagination.html

No comments:

Post a Comment