want to show titles using i18n Above is the image for showing titles 'items per page'
First, create a custom MatPaginatorIntl
that uses Transloco
for translation.
import { MatPaginatorIntl } from '@angular/material/paginator';
import { TranslocoService } from '@ngneat/transloco';
export class TranslocoPaginatorIntl extends MatPaginatorIntl {
constructor(private _translocoService: TranslocoService) {
super();
this._translocoService.selectTranslateObject('table').subscribe((translation) => {
this.itemsPerPageLabel = translation.itemsPerPage;
this.nextPageLabel = translation.nextPage;
this.previousPageLabel = translation.previousPage;
this.firstPageLabel = translation.firstPage;
this.lastPageLabel = translation.lastPage;
this.getRangeLabel = (page, pageSize, length) => {
if (length === 0 || pageSize === 0) {
return `0 ${translation.of} ${length}`;
}
length = Math.max(length, 0);
const startIndex = page * pageSize;
const endIndex =
startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize;
return `${startIndex + 1} - ${endIndex} ${translation.of} ${length}`;
};
// This is required to update the paginator labels after the translation is loaded
this.changes.next();
});
}
}
In this code, TranslocoPaginatorIntl
is a custom MatPaginatorIntl
that uses Transloco
for translations. It subscribes to the translations for the 'table'
key and updates the labels accordingly.
Then, you need to provide TranslocoPaginatorIntl
in your module:
import { MatPaginatorIntl } from '@angular/material/paginator';
import { TranslocoModule, TranslocoService } from '@ngneat/transloco';
import { TranslocoPaginatorIntl } from './your/path/to/transloco-paginator-intl';
@NgModule({
imports: [
// ... other modules
TranslocoModule,
],
providers: [
// ... other providers
{
provide: MatPaginatorIntl,
useClass: TranslocoPaginatorIntl,
deps: [TranslocoService],
},
],
// ... other properties
})
export class YourModule {}
In this code,
{
provide: MatPaginatorIntl,
useClass: TranslocoPaginatorIntl,
deps: [TranslocoService],
},
tells Angular to use TranslocoPaginatorIntl
instead of the default MatPaginatorIntl
.
NOTE:
Remember to replace 'table'
with the actual key in your translation files, and replace the translation keys (itemsPerPage
, nextPage
, etc.) with the actual keys in your translation files. My i18n setup is for en-us & zh-tw. The i18n json files sample are as follows:
en-us.json
{
"table": {
"search": "Search",
"keywords": "Keywords",
"itemsPerPage": "Items per page",
"nextPage": "Next page",
"previousPage": "Previous page",
"firstPage": "First page",
"lastPage": "Last page",
"of": "of",
"noData": "No data",
}
}
zh-tw.json:
{
"table": {
"search": "搜尋",
"keywords": "關鍵字",
"itemsPerPage": "每頁數量",
"nextPage": "下一頁",
"previousPage": "上一頁",
"firstPage": "第一頁",
"lastPage": "最後一頁",
"of": "從",
"noData": "沒有資料",
}
}