How to use paginator from material angular?

AngularPaginationAngular Material

Angular Problem Overview


I'm new to angular and trying to implement pagination in my app. I am trying to use this material component.

With the code below, I can get length, pagesize, and pageSizeOptions in my .ts file

<md-paginator [length]="length"
              [pageSize]="pageSize"
              [pageSizeOptions]="pageSizeOptions"
</md-paginator>

export class PaginatorConfigurableExample {

  length = 100;
  pageSize = 10;
  pageSizeOptions = [5, 10, 25, 100];

  }
}

but I can't seem to trigger a function to change the data on the table above when the page is changed. Also, how do I use the nextPage, previousPage, hasNextPage, and hasPreviousPage methods?

Angular Solutions


Solution 1 - Angular

I'm struggling with the same here. But I can show you what I've got doing some research. Basically, you first start adding the page @Output event in the foo.template.ts:

 <md-paginator #paginator
                [length]="length"
                [pageIndex]="pageIndex"
                [pageSize]="pageSize"
                [pageSizeOptions]="[5, 10, 25, 100]"
                (page)="pageEvent = getServerData($event)"
                >
 </md-paginator>

And later, you have to add the pageEvent attribute in the foo.component.ts class and the others to handle paginator requirements:

pageEvent: PageEvent;
datasource: null;
pageIndex:number;
pageSize:number;
length:number;

And add the method that will fetch the server data:

ngOnInit() {
   getServerData(null) ...
}

public getServerData(event?:PageEvent){
  this.fooService.getdata(event).subscribe(
    response =>{
      if(response.error) {
        // handle error
      } else {
        this.datasource = response.data;
        this.pageIndex = response.pageIndex;
        this.pageSize = response.pageSize;
        this.length = response.length;
      }
    },
    error =>{
      // handle error
    }
  );
  return event;
}

So, basically, every time you click the paginator, you'll activate getServerData(..) method that will call foo.service.ts getting all data required. In this case, you do not need to handle nextPage and nextXXX events because they will be automatically calculated upon view rendering.

I hope this can help you. Let me know if you had success. =]

Solution 2 - Angular

Hey so I stumbled upon this and got it working, here is how:

inside my component.html

<mat-paginator #paginator [pageSize]="pageSize" [pageSizeOptions]="[5, 10, 20]" [showFirstLastButtons]="true" [length]="totalSize"
    [pageIndex]="currentPage" (page)="pageEvent = handlePage($event)">
</mat-paginator>

Inside my component.ts

public array: any;
public displayedColumns = ['', '', '', '', ''];
public dataSource: any;    

public pageSize = 10;
public currentPage = 0;
public totalSize = 0;

@ViewChild(MatPaginator) paginator: MatPaginator;

constructor(private app: AppService) { }

ngOnInit() {
  this.getArray();
}

public handlePage(e: any) {
  this.currentPage = e.pageIndex;
  this.pageSize = e.pageSize;
  this.iterator();
}

private getArray() {
  this.app.getDeliveries()
    .subscribe((response) => {
      this.dataSource = new MatTableDataSource<Element>(response);
      this.dataSource.paginator = this.paginator;
      this.array = response;
      this.totalSize = this.array.length;
      this.iterator();
    });
}

private iterator() {
  const end = (this.currentPage + 1) * this.pageSize;
  const start = this.currentPage * this.pageSize;
  const part = this.array.slice(start, end);
  this.dataSource = part;
}

All the paging work is done from within the iterator method. This method works out the skip and take and assigns that to the dataSource for the Material table.

Solution 3 - Angular

based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

Paginator html and list

<mat-paginator [length]="localNewspapers.length" pageSize=20
               (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
               showFirstLastButtons="false">
</mat-paginator>
<mat-list>
   <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                         slice: lowValue : highValue)"
                         [newspaper]="paper"> 
  </app-newspaper-pagi-item>

Component logic

import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";

@Component({
  selector: 'app-uniques-newspaper-list',
  templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
  lowValue: number = 0;
  highValue: number = 20;

  // used to build a slice of papers relevant at any given time
  public getPaginatorData(event: PageEvent): PageEvent {
    this.lowValue = event.pageIndex * event.pageSize;
    this.highValue = this.lowValue + event.pageSize;
    return event;
  }

}

Solution 4 - Angular

Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.

View:

 <div class="col-md-3" *ngFor="let productObj of productListData | 
     slice: lowValue : highValue">
       //actual data dispaly  
 </div>

<mat-paginator [length]="productListData.length" [pageSize]="pageSize" 
   (page)="pageEvent = getPaginatorData($event)">
</mat-paginator> 

Component

    pageIndex:number = 0;
    pageSize:number = 50;
    lowValue:number = 0;
    highValue:number = 50;       
 
  getPaginatorData(event){
     console.log(event);
     if(event.pageIndex === this.pageIndex + 1){
        this.lowValue = this.lowValue + this.pageSize;
        this.highValue =  this.highValue + this.pageSize;
       }
    else if(event.pageIndex === this.pageIndex - 1){
       this.lowValue = this.lowValue - this.pageSize;
       this.highValue =  this.highValue - this.pageSize;
      }   
       this.pageIndex = event.pageIndex;
 }

Solution 5 - Angular

Component:

import { Component,  AfterViewInit, ViewChild } from @angular/core;
import { MatPaginator } from @angular/material;

export class ClassName implements AfterViewInit {
    @ViewChild(MatPaginator) paginator: MatPaginator;
    length = 1000;
    pageSize = 10;
    pageSizeOptions: number[] = [5, 10, 25, 100];

    ngAfterViewInit() {
        this.paginator.page.subscribe(
           (event) => console.log(event)
    );
}

HTML

<mat-paginator 
   [length]="length"
   [pageSize]="pageSize" 
   [pageSizeOptions]="pageSizeOptions"
   [showFirstLastButtons]="true">
</mat-paginator>

Solution 6 - Angular

The issue in the original question is that you are not capturing "page" event, to resolve this you need to add (page)='yourEventHandler($event)' as an attribute in the md-paginator tag.

check a working example here

You can also check the API docs here

Solution 7 - Angular

After spending few hours on this i think this is best way to apply pagination. And more importantly it works. This is my paginator code <mat-paginator #paginatoR [length]="length" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions">

Inside my component @ViewChild(MatPaginator) paginator: MatPaginator; to view child and finally you have to bind paginator to table dataSource and this is how it is done ngAfterViewInit() {this.dataSource.paginator = this.paginator;} Easy right? if it works for you then mark this as answer.

Solution 8 - Angular

This issue is resolved after spending few hours and i got it working. which is believe is the simplest way to solve the pagination with angular material.

  • Do first start by working on (component.html) file

and do in the (component.ts) file

 import { MatPaginator } from '@angular/material/paginator';
 import { Component, OnInit, ViewChild } from '@angular/core';

 export interface UserData {
 full_name: string;
 email: string;
 mob_number: string;
 }
 
 export class UserManagementComponent implements OnInit{
  dataSource : MatTableDataSource<UserData>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  
  constructor(){
    this.userList();
   }
   
    ngOnInit() { }

   public userList() {

   this._userManagementService.userListing().subscribe(
      response => {

      console.log(response['results']);
      this.dataSource = new MatTableDataSource<UserData>(response['results']);
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);

     },


      error => {});

     }

 }

Remember Must import the pagination module in your currently working module(module.ts) file.

  import {MatPaginatorModule} from '@angular/material/paginator';

   @NgModule({
      imports: [MatPaginatorModule]
    })

Hope it will Work for you.

Solution 9 - Angular

The tricky part here is to handle is the page event. We can follow angular material documentation up to defining page event function.

Visit https://material.angular.io/components/paginator/examples for the reference.

I will add my work with hours of hard work in this regard. in the relevant HTML file should look like as follows,

<pre>
<mat-paginator
    [pageSizeOptions]="pageSizeOptions"
    [pageSize]="Size"
    (page)="pageEvent = pageNavigations($event)"
    [length]="recordCount">
</mat-paginator>
</pre>

Then go to the relevant typescript file and following code,

declarations,

@Input('data') customers: Observable<Customer[]>;
pageEvent: PageEvent;
Page: number=0;
Size: number=2;
recordCount: number;
pageSizeOptions: number[] = [2,3,4,5];

The key part of page navigation as follows,

pageNavigations(event? : PageEvent){
    console.log(event);
    this.Page = event.pageIndex;
    this.Size = event.pageSize;
    this.reloadData();
  }

We require the following function to call data from the backend.

reloadData() {

    this.customers = this.customerService.setPageSize(this.Page ,this.Size);
    this.customerService.getSize().subscribe(res => {
      this.recordCount = Number(res);
     
      console.log(this.recordCount);
    });
  }

Before the aforementioned implementation, our services file should contain the following service call

setPageSize(page: number, size: number): Observable<any> {
    return this.http.get(`${this.baseUrl}?pageSize=${size}&pageNo=${page}`);
  }

Then all set to go and enable pagination in our app. Feel free to ask related questions thank you.

Solution 10 - Angular

THIS WORKS FOR ME:

Make sure that you define the datasource in the ngOnInit() (avoid doing it in the ngViewAfterInit function).. something like this

dataSource: MatTableDataSource<Listing> = new MatTableDataSource();
pageEvent: PageEvent;
datasource: null;
pageSizeOptions: number[] = [5, 10, 12, 15];
pageIndex: number;
pageSize: number;
length: number;

constructor(private yourService: YourService) {
}
ngOnInit() {
   this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
   this.pageIndex=0;
   this.pageSize=10;
   this.yourService.getListItems(this.pageSize, 
   this.pageIndex).subscribe(res => {
          this.dataSource.data = res;
          this.lenght=res.lenght();
       });
   }  
handlePageEvent(event: PageEvent) {
   this.yourService.getListItems(event.pageSize, 
   event.pageIndex).subscribe(e=>{
     this.dataSource.data = res;
});       
return event;
}

 

And your html component like this

 <mat-paginator (page)="handlePageEvent($event)"
      [pageSizeOptions]="pageSizeOptions"
      [pageSize]="pageSize"
      class="sticky left-0"
      [length]="length"
      [pageIndex]="pageIndex"
      aria-label="Select page"
  ></mat-paginator>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrunken DaddyView Question on Stackoverflow
Solution 1 - AngularaelkzView Answer on Stackoverflow
Solution 2 - AngularWesley CoetzeeView Answer on Stackoverflow
Solution 3 - AngularavokadoView Answer on Stackoverflow
Solution 4 - AngularAsridh KumarView Answer on Stackoverflow
Solution 5 - AngularVireeView Answer on Stackoverflow
Solution 6 - AngularLH7View Answer on Stackoverflow
Solution 7 - AngularChetan SharmaView Answer on Stackoverflow
Solution 8 - Angulargunjan girdharView Answer on Stackoverflow
Solution 9 - AngularMohamed NaasirView Answer on Stackoverflow
Solution 10 - AngularShoniisraView Answer on Stackoverflow