typescriptpaginationangular-materialangular6

How To Change itemsPerPageLabel in mat-paginator in Angular 6+


I am using Angular 6.0.3 with Angular Material 7.1.0, I have my paginator in a separate component (that is not the app.component). What I have tried so far:

Created separate ts file called myPagniator.ts:

import {MatPaginatorIntl} from '@angular/material';

export class MyPaginatorLabel extends MatPaginatorIntl {

  itemsPerPageLabel = 'custome_label_name'; // customize item per page label

  constructor() {
    super();
  }
}

In my app.module.ts : I imported both MatPaginatorModule, MatPaginatorIntl from Angular Material. Inside providers array of app.module.ts, I put in MyPaginatorLabel and MatPaginatorIntl.

In the component which is using Angular MatPaginator, I extends MyPaginatorLabel class and have its constructor calls super() method, still it displays default text "itemsPerPage" after all this

What have I done wrong here ?? Can someone give me a bit of hint ?


Solution

  • Create a new TypeScript file and add a function that is exported and returns a MatPaginatorIntl object.

    To modify the labels and text displayed, create a new instance of MatPaginatorIntl and include it in a custom provider - Angular Material - Paginator > API

    CustomPaginatorConfiguration.ts

    import { MatPaginatorIntl } from '@angular/material';
    
    export function CustomPaginator() {
      const customPaginatorIntl = new MatPaginatorIntl();
    
      customPaginatorIntl.itemsPerPageLabel = 'Custom_Label:';
    
      return customPaginatorIntl;
    }
    

    Then add it to app.module.ts:

    import { MatPaginatorIntl } from '@angular/material';
    import { CustomPaginator } from './app/CustomPaginatorConfiguration';
    
    @NgModule({
      // ...
      providers: [
        { provide: MatPaginatorIntl, useValue: CustomPaginator() }
      ]
    })
    

    You can also set the setting for a particular component like:

    import { CustomPaginator } from './CustomPaginator';
    import { MatPaginatorIntl } from '@angular/material';
    /**
     * @title Paginator
     */
    @Component({
      selector: 'your_component',
      templateUrl: 'your_component.html',
      providers: [
        { provide: MatPaginatorIntl, useValue: CustomPaginator() }  // Here
      ]
    })
    

    StackBlitz