Sergio Mendez
Sergio Mendez

Reputation: 1519

How to use Angular 2 Translate service pipe in code?

Here is the thing... I'm using an angular 4 template in my app, and this has a good working translate service. The problem is that I don't know how to use that pipe in code.

In HTML just put <span>{{ this.variable | traslate }}</span> and then, the service go to some JSON files to find the text and translate.

Here is the code in my component.ts

const SMALL_WIDTH_BREAKPOINT = 960;
@Component({
  selector: 'app-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.scss']
})

export class TrackingComponent implements OnInit { 
  currentLang = 'es';
  private mediaMatcher: MediaQueryList = matchMedia(`(max-width: 
  ${SMALL_WIDTH_BREAKPOINT}px)`);
  constructor(
    public translate: TranslateService,
    zone: NgZone,
    private router: Router,
  ) {
    const browserLang: string = translate.getBrowserLang();
      translate.use(browserLang.match(/en|es/) ? browserLang : 'es');
      this.mediaMatcher.addListener(mql => zone.run(() => {
        this.mediaMatcher = mql;
      }));
      translate.use(this.currentLang);
  }

  ngOnInit() { }

  myFunction(msg: string) : {
    const translatedText = msg; // HERE IS WHERE I WANT TO USE THE TRANSLATE SERVICE BUT I DON'T KNOW HOW TO CALL IT
    alert(translatedText );
  }

}

Yes, I put all the needed things in the module, because it works in HTML... but I don't know how to call it in the code.

I was searching how to solve my problem and I found This:

 let translatedText = new TranslatePipe().transform(msg);

 but the `TranslatePipe` does not work. 

Anyone knows how to call it?

Upvotes: 2

Views: 3485

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222682

You have basically 3 choices

If you are absolutely sure that your translation files are already loaded and you don't want to update the translations automatically if a language changes use

translate.instant('ID')

If you are not sure about the loading state but you don't need updates on language changes use translate.get('ID'). It gives you an observable that returns the translation once it's loaded and terminates the observable.

If you want constant updates (e.g. when a language changes) use translate.stream('ID') - it returns an observable that emits translation updates. Make sure to dispose the observable if you don't need it anymore.

This assumes that you've injected TranslationService as translate in your component.

E.g.

export class AppComponent {
    constructor(translate: TranslateService) {
        translate.get('hello.world').subscribe((text:string) => {console.log(text});
    }
}

You'll have to assign the translation to your data array from within the subscribe

Upvotes: 6

Related Questions