1

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? (This is not true after some research)

The solution is use a constructor and import the TranslateService.

Babulaas
  • 761
  • 3
  • 13
  • 47

2 Answers2

2

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.

David Mališ
  • 196
  • 4
  • but how can you update the translation when the language is changed. you can subscribe to .onLangChange but the transform is already executed. You stay on the same page only you switch between languages. – Babulaas Dec 23 '21 at 14:14
  • found it here: https://stackoverflow.com/a/48697426/4198589. just set the pure to false – Babulaas Dec 23 '21 at 14:21
  • But I also read that this is not good for performance. is there another solution? – Babulaas Dec 23 '21 at 14:28
1

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>