简体   繁体   中英

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

I am using ngx-translate for my translations in my angular app.

In a custom pipe I have some text that need to be translated.

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;
    }
  }

}

As far as I know a constructor is not suppported since angular 6. How can I translate the text in a 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>

In Angular 9 and with ngx-translate/core 12.1.x, I am able to inject a TranslationService into a Pipe and use it.

In order to be able to do that, you need to have an import of TranslateModule.forRoot({...}) somewhere, for example I have it in my main AppModule 's imports.

    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;
        }
    
      }
    
    }

Note that you also have a translate pipe available from ngx-translate as someone already mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM