MatPaginator를 번역하는 방법

6545 단어 typescriptangular
Angular 애플리케이션을 빌드할 때 종종 Angular의 Material Design Components가 사용됩니다. 많은 사용 사례에서 애플리케이션을 번역해야 합니다. 다양한 번역 모듈을 사용할 수 있습니다. 애플리케이션에 페이지네이터가 있는 테이블이 있는 경우 문자열을 변경하는 것보다 조금 더 복잡해집니다.

MatPaginator 또는 <mat-paginator>는 일반적으로 테이블과 함께 사용되는 페이지 정보에 대한 탐색을 제공합니다.

각 페이지네이터 인스턴스에는 다음이 필요합니다.
  • 페이지당 항목 수(기본값은 50으로 설정됨)
  • 페이징 중인 총 항목 수
  • 현재 페이지 인덱스의 기본값은 0이지만 pageIndex를 통해 명시적으로 설정할 수 있습니다.

  • 페이지네이터는 사용자가 선택할 수 있는 페이지 크기 드롭다운을 표시합니다. 이 드롭다운에 대한 옵션을 설정할 수 있습니다.

    하나의 번역만

    Angular provides the MatPaginatorIntl so you can internationalize the labels, though if you only want to translate into one language, you can do it likes this:

    this.paginator._intl.itemsPerPageLabel = 'Items pro Seite';
    this.paginator._intl.nextPageLabel = 'Nächste';
    this.paginator._intl.previousPageLabel = 'Vorherige';
    

    The future-proof way would be to provide an own instance of MatPaginatorIntl .

    국제화

    The labels for the paginator can be customized by providing your own instance of MatPaginatorIntl .

    This will allow you to change the following:

    • The label for the length of each page.
    • The range text displayed to the user.
    • The tooltip messages on the navigation buttons.
    Let's walk through an example with using ngx-translate .

    1. 주사 가능한 클래스 생성

    The class subscribes to language changes, also unsubscribes onDestroy, and updates the translations accordingly, for more details visit Github - Angular Issue/Feature .

    import { Injectable, OnDestroy } from '@angular/core';
    import { MatPaginatorIntl } from '@angular/material';
    import { TranslateService } from '@ngx-translate/core';
    import { Subject } from 'rxjs/Subject';
    
    @Injectable()
    export class CustomMatPaginatorIntl extends MatPaginatorIntl
      implements OnDestroy {
      unsubscribe: Subject<void> = new Subject<void>();
      OF_LABEL = 'of';
    
      constructor(private translate: TranslateService) {
        super();
    
        this.translate.onLangChange
          .takeUntil(this.unsubscribe)
          .subscribe(() => {
            this.getAndInitTranslations();
          });
    
        this.getAndInitTranslations();
      }
    
      ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
      }
    
      getAndInitTranslations() {
        this.translate
          .get([
            'PAGINATOR.ITEMS_PER_PAGE',
            'PAGINATOR.NEXT_PAGE',
            'PAGINATOR.PREVIOUS_PAGE',
            'PAGINATOR.OF_LABEL',
          ])
          .takeUntil(this.unsubscribe)
          .subscribe(translation => {
            this.itemsPerPageLabel =
              translation['PAGINATOR.ITEMS_PER_PAGE'];
            this.nextPageLabel = translation['PAGINATOR.NEXT_PAGE'];
            this.previousPageLabel =
              translation['PAGINATOR.PREVIOUS_PAGE'];
            this.OF_LABEL = translation['PAGINATOR.OF_LABEL'];
            this.changes.next();
          });
      }
    
      getRangeLabel = (
        page: number,
        pageSize: number,
        length: number,
      ) => {
        if (length === 0 || pageSize === 0) {
          return `0 ${this.OF_LABEL} ${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} ${
          this.OF_LABEL
        } ${length}`;
      };
    }
    


    💰: Start your cloud journey with $100 in free credits with DigitalOcean!

    2. 가져오기 및 업데이트 공급자

    Import and add the class in providers in your app.module.ts file.

    import { CustomMatPaginatorIntl } from './shared/custom-mat-paginator-intl';
    
    providers: [
      {
        provide: MatPaginatorIntl,
        useClass: CustomMatPaginatorIntl,
      },
    ];
    

    3. 완료

    🎉🎉🎉 Congratulations! 🎉🎉🎉

    You have successfully internationalized MatPaginator .

    TL;DR

    Material Design Components from Angular make a lot of things easier, unfortunately translating the paginator is not one of them. To provide a translation you have to:

    • Create an injectable class, which listens to language changes and updates translations
    • Provide translation in app.module
    Thanks for reading and if you have any questions , use the comment function or send me a message . If you want to know more about Angular Angular Tutorials .

    참조(큰 감사): Google - Angular , Konrad Klimczak , Github - Angular Issue/Feature

    좋은 웹페이지 즐겨찾기