Home > Software engineering >  mat-paginator does not show page info
mat-paginator does not show page info

Time:04-30

Material paginator does not show page info.

In official documentation, there is page info: 'Page 1 of 20' but when I run their own code locally, or in Stackblitz there is different output.

It shows number of items: '1-10 of 100'

I am running same version as documentation

Is this bug, or did I messed up some property setup?

See images:

mat docu: enter image description here

stackblitz: enter image description here

CodePudding user response:

There is a property called getRangeLabel available for MatPaginator. You can use it to change the label as you want.

In your component, set up your paginator:

@ViewChild(MatPaginator, {static : false}) paginator!: MatPaginator;

Then assign a custom function in the afterViewInit:

ngAfterViewInit() {

    this.paginator._intl.itemsPerPageLabel = 'Your custom text';
 }

------------------------ OR ------------------------

ngAfterViewInit() {
    this.paginator._intl.getRangeLabel = this.getRangeDisplayText;
  }

Then set up a custom function to display the text you need:

getRangeDisplayText = (page: number, pageSize: number, length: number) => {
  const initialText = `Displaying users`;  // customize this line
  if (length == 0 || pageSize == 0) {
    return `${initialText} 0 of ${length}`;
  }
  length = Math.max(length, 0);
  const startIndex = page * pageSize;
  const endIndex = startIndex < length 
    ? Math.min(startIndex   pageSize, length) 
    : startIndex   pageSize;
  return `${initialText} ${startIndex   1} to ${endIndex} of ${length}`; // customize this line
};

This will use whatever pageSize and length you have in your HTML or have configured in your component.

<mat-paginator [length]="dataSource.total"
      [pageSize]="10"
      hidePageSize
      showFirstLastButtons>

If your data returns 50 records, this will show this text:

Displaying users 1 to 10 of 50

CodePudding user response:

one possible fix that I came up with is add custom element

ngAfterViewInit(): void {  
    // get mat sub component
    const list = this.customPagingItems.nativeElement.getElementsByClassName("mat-paginator-range-actions");
    if (!!list[0]) {    
      // add page info element
      const div = this.renderer.createElement("div");
      this.renderer.addClass(div, "mat-paginator-page-info");
      list[0].appendChild(div);
    }
  }

  ngAfterViewChecked() {
    // update page info because mat-paginator is missing that
    const list = this.customPagingItems.nativeElement.getElementsByClassName("mat-paginator-page-info");
    if (!!list[0]) list[0].innerHTML = `Page ${this.currentPage.toString()} of ${this.totalPages.toString()}`;
  }

order of elements is done in CSS by adding order property since it is display:flex (no need of directive overkill)

  • Related