Implement Serverside Pagination In Angular Material In Angular

What is Server-side pagination?

  • Making queries that bring in one page of data at a time is what server-side paging entails. The actual commands required to access the data are determined by the API that the server has made available.

Step1: Create New Angular Application.

ng new Demo

Step2: Write below code in gallery.component.html

<div class="main">
  <div class="example-container mat-elevation-z8">
    <div class="example-table-container">
      <mat-table [dataSource]="dataSource" class="example-table gallery-tbl" matSort #galleryTable>
        <!-- Number Column -->
        <ng-container matColumnDef="Date">
          <th *matHeaderCellDef  class="date_width">Date</th>
          <td *matCellDef="let element" class="date_width">{{element.datetime | date}}</td>
        </ng-container>
        <!-- Title Column -->
        <ng-container matColumnDef="Time">
          <th *matHeaderCellDef class="title_per" >Title</th>
          <td *matCellDef="let element" class="title_per">{{element.status_text}}</td>
        </ng-container>
        
        <ng-container matColumnDef="NewPersons">
          <th *matHeaderCellDef class="text-start new_all" >New Persons</th>
          <td *matCellDef="let element" class="text-start new_all">{{element.new_persons}}</td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </mat-table>
    </div>
  </div>
</div>

Step3: Write below code in gallery.component.ts

Here, First call the function getAllGalleryData() in this function call api and passing the pagecount=0 then getting first time 20 records in result and assign the datasource.

Now, user can reach table scroll the end of the page than call the  onTableScroll() that return the incremented page number data getting response from server side and assing the existing dataSource.

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { debounceTime, fromEvent, Subscription } from 'rxjs';
import { gallery } from 'src/app/dtos/gallerydtos/gallery';
import { CommonService } from 'src/app/services/common.service';
import { GalleryService } from 'src/app/services/gallery/gallery.service';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.css'],
})
export class GalleryComponent implements OnInit {

  @ViewChild('galleryTable', {read: ElementRef}) public tableRef!: ElementRef;
  ELEMENT_DATA: gallery[] = [];
  datetime: Date = new Date();
  start: number = 0;
  limit: number = 15;
  end: number = this.limit + this.start;
  datas: any = [];
  displayedColumns = [
    'Date',
    'Time',
    'NewPersons'
  ];
  dataSource = this.ELEMENT_DATA;
  select: any;
  count:number = 1;
  pageCount:number = 1;
  
  constructor(
    private _galleryService: GalleryService,
    private _commonserviceService: CommonService,  
  ) {}

  ngOnInit(): void {
    this.getAllGalleryData();
  }

  public ngAfterViewInit(): void {
    fromEvent(this.tableRef.nativeElement, 'scroll')
         .pipe(debounceTime(700))
         .subscribe((e: any) => this.onTableScroll(e));
  }

  getAllGalleryData() {
    this._galleryService.getGalleryData(0).subscribe((res: any) => {
      this.dataSource = res.syncs;
    });
  }

  onTableScroll(event: any) {
    const tableViewHeight = event.target.offsetHeight;
    const tableScrollHeightt = event.target.scrollHeight;
    const scrollLocation = event.target.scrollTop;
    const buffer = 200;
    const limit = tableScrollHeightt - tableViewHeight - buffer; 
    if(scrollLocation > limit){
      if(this.pageCount <= this.totalPages){
        this._galleryService.getGalleryData(this.pageCount).subscribe((res: any) => {
          res.syncs.forEach((_element: any) => {
               this.dataSource.push(_element);
               this.dataSource = [...this.dataSource];
          });
          if(this.pageCount <= this.totalPages){
            this.pageCount++;
          }
        });
      }
    }
  }
  
}

Step4: Write below code in gallery.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { syncsDropdown } from 'src/app/dtos/gallerydtos/gallery';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root',
})
export class GalleryService {

  constructor(private httpclient: HttpClient) {}

  getGalleryData(pageNo: any) {
    return this.httpclient.get(
      `${environment.dnaApi}/gallery/list?page=${pageNo}`
    );
  }
  
}

Step5: Apply CSS in your gallery.component.css

.mat-table {
  overflow: auto;
  max-height: 755px;
}

table {
  width: 100%;
}

.mat-table {
  background: #171717;
  width: 100%;
}

.gallery-tbl tr td:not(:last-child){
   padding: 33px 10px !important;
   font-size: 16px;
   color: white;
   opacity: 0.8;
   font-weight: 100;
   font-family: 'Inter Thin';
}

.gallery-tbl tr td:last-child{
  font-size: 16px;
   color: white;
   opacity: 0.8;
   font-weight: 100;
   font-family: 'Inter Thin';
}

th{
  font-family: 'Inter bold';
  color: white;
  font-size: 16px;
  font-weight: bold;
  padding: 0px 10px;
}

Step6: Now Run Project. npm start

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories