pageevent matpaginatorintl matpaginator itemsperpagelabel example angular angular-material2

angular - itemsperpagelabel - matpaginatorintl example



¿Cómo usar MatPaginatorIntl? (8)

Estoy usando el componente MatPaginator y estoy tratando de averiguar cómo traducir esas etiquetas (la documentación no es lo suficientemente clara).

Encontré este artículo que muestra cómo hacer esto y seguí los pasos:

1 - Creé un archivo llamado custom-paginator.ts y coloqué lo siguiente:

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 - En app.module.ts pongo:

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

Sin embargo, simplemente no cambia nada. ¿Qué me estoy perdiendo?


Además, puede utilizar los servicios inyectados marcando el Intl para que sea un inyectable en sí mismo. Vea el ejemplo (ignore los detalles específicos de DoneSubject y LocalizeService, ya que son implementaciones personalizadas):

import { Injectable, OnDestroy } from ''@angular/core''; import { MatPaginatorIntl } from ''@angular/material''; import { LocalizeService } from ''app/general''; import { DoneSubject } from ''app/rx''; import { takeUntil } from ''rxjs/operators''; @Injectable() export class MatPaginatorIntlLoc extends MatPaginatorIntl implements OnDestroy { constructor(private readonly localizer: LocalizeService) { super(); localizer.locale$.pipe(takeUntil(this.done$)).subscribe(() => { this.itemsPerPageLabel = localizer.translate(''mat paginator label: items per page''); this.nextPageLabel = localizer.translate(''mat paginator label: next page''); this.previousPageLabel = localizer.translate(''mat paginator label: previous page''); this.firstPageLabel = localizer.translate(''mat paginator label: first page''); this.lastPageLabel = localizer.translate(''mat paginator label: last page''); }); } private readonly done$ = new DoneSubject(); ngOnDestroy() { this.done$.done(); } getRangeLabel = (page: number, pageSize: number, length: number) => this.localizer .translate(''mat paginator label: x of y'', [ length > 0 && pageSize > 0 ? (page * pageSize + 1) + '' - '' + Math.min((page + 1) * pageSize, Math.max(length, 0)) : 0, Math.max(length, 0), ]); }

Y no olvides incluirlo en tu módulo:

providers: [ ... { provide: MatPaginatorIntl, useClass: MatPaginatorIntlLoc }, ... ]


Basado en el código Vinko Vorih, hice un paginador trabajando con ngx-translate, aquí está el código:

import { Injectable } from ''@angular/core''; import { MatPaginatorIntl } from ''@angular/material''; import { TranslateService } from "@ngx-translate/core"; export class PaginatorIntlService extends MatPaginatorIntl { translate: TranslateService; itemsPerPageLabel = ''Items per page''; nextPageLabel = ''Next page''; previousPageLabel = ''Previous page''; getRangeLabel = function (page, pageSize, length) { const of = this.translate ? this.translate.instant(''paginator.of'') : ''of''; if (length === 0 || pageSize === 0) { return ''0 '' + of + '' '' + 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 + '' '' + of + '' '' + length; }; injectTranslateService(translate: TranslateService) { this.translate = translate; this.translate.onLangChange.subscribe(() => { this.translateLabels(); }); this.translateLabels(); } translateLabels() { this.itemsPerPageLabel = this.translate.instant(''paginator.items_per_page''); this.nextPageLabel = this.translate.instant(''paginator.next_page''); this.previousPageLabel = this.translate.instant(''paginator.previous_page''); } }

Y luego en su entrada de proveedores de módulos:

{ provide: MatPaginatorIntl, useFactory: (translate) => { const service = new PaginatorIntlService(); service.injectTranslateService(translate); return service; }, deps: [TranslateService] }

De esta manera, puede almacenar las traducciones en su archivo i18n habitual y, si su aplicación web puede cambiar la configuración regional de manera dinámica, el paginador se traducirá a pedido.


Hice algunas modificaciones para corregir el índice final cuando el índice de inicio excede la longitud de la lista. También agrego la traducción para la primera y última página. Es para componente de paginación @ angular / material 5.2.4.

import { Injectable } from ''@angular/core''; import { MatPaginatorIntl } from ''@angular/material''; import { TranslateService } from ''@ngx-translate/core''; @Injectable() export class MatPaginationIntlService extends MatPaginatorIntl { translate: TranslateService; firstPageLabel = ''First page''; itemsPerPageLabel = ''Items per page''; lastPageLabel = ''Last page''; nextPageLabel = ''Next page''; previousPageLabel = ''Previous page''; getRangeLabel = (page: number, pageSize: number, length: number): string => { const of = this.translate ? this.translate.instant(''mat-paginator-intl.of'') : ''of''; if (length === 0 || pageSize === 0) { return ''0 '' + of + '' '' + length; } length = Math.max(length, 0); const startIndex = ((page * pageSize) > length) ? (Math.ceil(length / pageSize) - 1) * pageSize: page * pageSize; const endIndex = Math.min(startIndex + pageSize, length); return startIndex + 1 + '' - '' + endIndex + '' '' + of + '' '' + length; }; injectTranslateService(translate: TranslateService) { this.translate = translate; this.translate.onLangChange.subscribe(() => { this.translateLabels(); }); this.translateLabels(); } translateLabels() { this.firstPageLabel = this.translate.instant(''mat-paginator-intl.first_page''); this.itemsPerPageLabel = this.translate.instant(''mat-paginator-intl.items_per_page''); this.lastPageLabel = this.translate.instant(''mat-paginator-intl.last_page''); this.nextPageLabel = this.translate.instant(''mat-paginator-intl.next_page''); this.previousPageLabel = this.translate.instant(''mat-paginator-intl.previous_page''); } }


Inyecte MatPaginatorIntl en cualquier lugar de su aplicación, configure las traducciones deseadas y llame a changes.next (). Repita en cada cambio de idioma (por ejemplo, suscribiéndose a onLangChange cuando se utiliza ngx-translate).


Para actualizar la etiqueta, puede activar un evento de cambio después de cambiar la etiqueta:

translateLabels() { this.firstPageLabel = this.translate.instant(''mat-paginator-intl.first_page''); ... this.changes.next(); }


Puedes hacerlo de esta manera: te estoy proporcionando etiquetas croatas:

customClass.ts

import {MatPaginatorIntl} from ''@angular/material''; 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; }; }

y AppModule.ts:

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

Funciona muy bien

Además, debe importar en su appModule.ts tanto MatPaginatorIntl como MatPaginatorIntlCro


Tuve el mismo problema y luego cambié en app.module.ts en la declaración de importaciones TranslateModule a TranslateModule.forRoot ()

Así que se ve así:

imports: [ ... TranslateModule.forRoot() ... ]

Cita del sitio de NPM: "El método forRoot static es una convención que proporciona y configura servicios al mismo tiempo. Asegúrese de que solo llame a este método en el módulo raíz de su aplicación, la mayoría de las veces, se llama AppModule. Este método le permite configure el TranslateModule especificando un cargador, un analizador y / o un controlador de traducción faltante ".

Aquí está el artículo completo: https://www.npmjs.com/package/@ngx-translate/core

Leer esto puede ayudar a resolver muchos problemas con TranslateModule!


en el archivo: matPaginatorIntlCroClass.ts

import {MatPaginatorIntl} from ''@angular/material''; export class MatPaginatorIntlCro extends MatPaginatorIntl { itemsPerPageLabel = ''Items par page''; nextPageLabel = ''Page Prochaine''; previousPageLabel = ''Page Précedente''; }

en Archivo: AppModule.ts:

import { MatPaginatorModule, MatPaginatorIntl} from ''@angular/material''; import { MatPaginatorIntlCro } from ''./matPaginatorIntlCroClass'' @NgModule({ imports: [], providers: [{ provide: MatPaginatorIntl, useClass: MatPaginatorIntlCro}], .. })

Fuente: MatPaginator