How to use MatPaginatorIntl?

dev_054 picture dev_054 · Oct 22, 2017 · Viewed 30.9k times · Source

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?

Answer

Vinko Vorih picture Vinko Vorih · Oct 23, 2017

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 = function (page, pageSize, length) {
    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}],