Published in


Translate your MatPaginator with ngx-translate and stay reactive!

Angular Material provides a lot of components to build rich apps using Material Design. One of them is a MatPaginator to control list or table pages. Additionally, it contains labels to inform a user about the current page or displayed elements range. The problem occurs when a developer tries to translate above-mentioned pieces of information using the most popular library to translating for Angular — @ngx-translate. The package is based on async translation with just in time change of selected language using RxJS Observables. On the other hand, MatPaginatorIntl — service with paginator translation — store labels as a string type. In the article, I present you how to translate non-reactive components and stay reactive!

In the official guide read that the labels for the paginator can be customized by providing your own instance of MatPaginatorIntl as a set of strings, so example service could look that:

Non-reactive MatPaginatorIntl example implementation.

In the beginning, we need to create a method for retrieving own translations. To achieve that, we inject the TranslateService inside a constructor and then fetch required labels in the created method using get from the injected service. Finally, we subscribe to the returned Observable and assign translations.

Retrieving translations from service.

Next step is to translate the range label produced by the getRangeLabel method. Common cases present a translation only of word and concatenation inside the method and it’s correct. The problem occurs when we use a more complex translation, g.e. Presented 10–20 of 100 products. In that case, we need to store all translations for one label. Instead of that, we can use one translation g.e. Presented {{start}} — {{end}} of {{length}} products and interpolate it using TranslateParser provided by the translate’s library.

Full translated service.

Some apps provide a possibility to change the language. To handle it in our case, we need to change a get to the stream method which returns a new value when language changed. Although, our service would be provided in the root, remember to unsubscribe stream with new values to avoid memory leaks g.e. in tests.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store