繁体   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