angulartypescriptangular-material

How to use MatPaginatorIntl?


I'm using MatPaginator component and I'm trying to figure out how to translate those labels (documentation isn't clear enough about this).

I've found this article showing how to do this and I followed the steps:

1 - I created a file called custom-paginator.ts and put the following there:

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

export class CustomPaginator extends MatPaginatorIntl {
  constructor() {
    super();
    this.nextPageLabel = ' My new label for next page';
    this.previousPageLabel = ' My new label for previous page';
    this.itemsPerPageLabel = 'Task per screen';
  }
}

2 - In app.module.ts I put:

@NgModule({
  // ...
  providers: [
    {
      provide: MatPaginatorIntl,
      useClass: CustomPaginator
    }
  ]
})
export class AppModule

However, it simply doesn't change nothing. What am I missing?


Solution

  • You can do it like this: I'm providing you with croatian labels:

    customClass.ts

    import { Injectable } from '@angular/core';
    import { MatPaginatorIntl } from '@angular/material/paginator';
    
    @Injectable()
    export class MatPaginatorIntlCro extends MatPaginatorIntl {
      itemsPerPageLabel = 'Stavki po stranici';
      nextPageLabel     = 'Slijedeća stranica';
      previousPageLabel = 'Prethodna stranica';
    
      getRangeLabel = (page: number, pageSize: number, length: number) => {
        if (length === 0 || pageSize === 0) {
          return '0 od ' + length;
        }
    
        length = Math.max(length, 0);
        const startIndex = page * pageSize;
        // If the start index exceeds the list length, do not try and fix the end index to the end.
        const endIndex = startIndex < length ?
          Math.min(startIndex + pageSize, length) :
          startIndex + pageSize;
        return startIndex + 1 + ' - ' + endIndex + ' od ' + length;
      };
    }
    

    and AppModule.ts:

    providers: [{ provide: MatPaginatorIntl, useClass: MatPaginatorIntlCro}],