Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ngx-translate in component

I'm using ngx-translate with no-problems in views, using pipes. What i need to do is to use it in a component, for example to show an error message, or define a datatable column default content.

I'm trying to do something like:

translate.instant("AREA.NEW");

or

translate.get("AREA.NEW").subscribe((res: string) => {
    console.log(res);
});

I've tried calling it in ngOnInit() and ngAfterViewInit()

But in both cases i just get "AREA.NEW", not the translated word. I asume the json dictionary is loaded after my call, so i don't realize how make it work.

like image 559
jonyjm Avatar asked Jul 25 '17 22:07

jonyjm


2 Answers

Import the TranslateService and use it wherever you want.

import { TranslateService } from '@ngx-translate/core';

export class YourComponent {
  constructor(private translateService: TranslateService) {
    console.log('translation', this.translateService.instant('my_i18n_json_defined_key'));
  }
}
like image 153
que1326 Avatar answered Oct 05 '22 23:10

que1326


It's work.

constructor(private readonly translateService: TranslateService) { }

ngOnInit() {
    this.translateService.get(['']).subscribe(translations => {
        console.info(this.translateService.instant('key1'));
        console.info(this.translateService.instant('key2'));
        console.info(this.translateService.instant('key3'));
    });
}
like image 40
Toshiaki Aizawa Avatar answered Oct 05 '22 22:10

Toshiaki Aizawa