Home > Software design >  Translate text in a custom angular pipe (ngx-translate)
Translate text in a custom angular pipe (ngx-translate)

Time:12-16

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?

CodePudding user response:

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>

CodePudding user response:

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.

  • Related