簡體   English   中英

翻譯自定義 angular pipe 中的文本(ngx 翻譯)

[英]Translate text in a custom angular pipe (ngx-translate)

我在我的 angular 應用程序中使用 ngx-translate 進行翻譯。

在自定義 pipe 中,我有一些需要翻譯的文本。

pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { Something} from '../domain';

@Pipe({
  name: 'someDescription'
})
export class SomeDescriptionPipe implements PipeTransform {

  transform(value: Something, args?: any): string {
    switch (value) {
      case Something.value1: return 'string 001';
      case Something.value2: return 'string 002';
      default: return value;
    }
  }

}

據我所知,自 angular 以來不支持構造函數 6. 如何翻譯 pipe 中的文本?

In below example "editProfile.timeZones."+timeZone?.key first pass into timezone pipe then into ngx translate pipe, you can do the same with your custome pipe and ngx translate pipe

<option *ngFor="let timeZone of timeZones" [value]="(timeZone?.key)">
                          {{ "editProfile.timeZones."+timeZone?.key | timezone | translate }}
</option>

在 Angular 9 和 ngx-translate/core 12.1.x 中,我能夠將TranslationService注入Pipe並使用它。

為了能夠做到這一點,您需要在某處導入TranslateModule.forRoot({...}) ,例如我在我的主要AppModule的導入中擁有它。

    import { Pipe, PipeTransform } from '@angular/core';
    import { Something} from '../domain';
    import { TranslateService } from '@ngx-translate/core';
    
    @Pipe({
      name: 'someDescription'
    })
    export class SomeDescriptionPipe implements PipeTransform {

      constructor(private _translateService: TranslateService) {
      }
    
      transform(value: Something, args?: any): string {
          //use translateService.instant('some.translation.key') function here


        switch (value) {
          case Something.value1: return 'string 001';
          case Something.value2: return 'string 002';
          default: return value;
        }
    
      }
    
    }

請注意,正如有人已經提到的那樣,您還可以從 ngx-translate 獲得translate pipe。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM