[angular] How to use paginator from material angular?

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?

This question is related to angular pagination angular-material

The answer is


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 an array 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;
  }

}

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>

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

 <mat-paginator [pageSizeOptions]="[2, 5, 10, 15, 20]" showFirstLastButtons>
 </mat-paginator>

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.


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.


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;
 }

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.


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


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.


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to pagination

How to use paginator from material angular? how to implement Pagination in reactJs In Flask, What is request.args and how is it used? Custom pagination view in Laravel 5 Simple pagination in javascript UITableView load more when scrolling to bottom like Facebook application How to use pagination on HTML tables? how to remove pagination in datatable Laravel Pagination links not including other GET parameters API pagination best practices

Examples related to angular-material

error TS1086: An accessor cannot be declared in an ambient context in Angular 9 @angular/material/index.d.ts' is not a module How to set width of mat-table column in angular? Confirm password validation in Angular 6 Set default option in mat-select Can't bind to 'dataSource' since it isn't a known property of 'table' Checkbox angular material checked by default How to set the color of an icon in Angular Material? Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) Styling mat-select in Angular Material