Angular ngx-translate usage in typescript
Asked Answered
C

9

61

I'm using this @ngx-translate/core i18n service and it works fine in templates (.html) with this syntax:

{{'my.i18n.key'|translate}}

Now I want to translate something in my component typescript file (.ts) but I don't know how to use it.

I can create translate object in my constructor:

constructor(private translate: TranslateService) {}

and now how to translate 'my.i18n.key' ?

Clipping answered 24/8, 2017 at 20:40 Comment(0)
S
51

From the doc on github:

get(key: string|Array, interpolateParams?: Object): Observable: Gets the translated value of a key (or an array of keys) or the key if the value was not found

try in your controller/class:

constructor(private translate: TranslateService) {
    let foo:string = this.translate.get('myKey');
}
Sympathin answered 24/8, 2017 at 23:35 Comment(4)
Thank You! Actually this returns translate object and I had to subscribe to get a string value like this: this.translate.get('my.i18n.key').subscribe(res => { console.log(res); });Clipping
That works like a charme. However, how can I check if there is a translateion, or it doesn't find any? When there's no translation for that key, it just returns that key in the observable, so I can't check the "success" of the translationKirimia
better constructor(private translate: TranslateService) { let foo:string = this.translate.stream('myKey'); }Monophony
@Monophony Subscribing to stream worked for me to update text in real time on language change, while instant and subscription to get would only trigger once.Wharton
E
109

To translate something in your typescript file, do the following

constructor(private translate: TranslateService) {}

then use like this wherever you need to translate

this.translate.instant('my.i18n.key')
Eliciaelicit answered 8/6, 2018 at 6:23 Comment(4)
this will return the translated string from the en.json (your language) fileEliciaelicit
should be this the correct answer... from doc /** * Returns a translation instantly from the internal state of loaded translation. * All rules regarding the current language, the preferred language of even fallback languages will be used except any promise handling. */Puglia
I am not sure, bit "instant" works only when the resource content is loaded, if instant is called before the loading of translation resources is finishe (ngOnIt - for example) it returns only the path to the resource.Rugen
Thank you, Friend! The solution is really simple and usable!Byyourleave
S
51

From the doc on github:

get(key: string|Array, interpolateParams?: Object): Observable: Gets the translated value of a key (or an array of keys) or the key if the value was not found

try in your controller/class:

constructor(private translate: TranslateService) {
    let foo:string = this.translate.get('myKey');
}
Sympathin answered 24/8, 2017 at 23:35 Comment(4)
Thank You! Actually this returns translate object and I had to subscribe to get a string value like this: this.translate.get('my.i18n.key').subscribe(res => { console.log(res); });Clipping
That works like a charme. However, how can I check if there is a translateion, or it doesn't find any? When there's no translation for that key, it just returns that key in the observable, so I can't check the "success" of the translationKirimia
better constructor(private translate: TranslateService) { let foo:string = this.translate.stream('myKey'); }Monophony
@Monophony Subscribing to stream worked for me to update text in real time on language change, while instant and subscription to get would only trigger once.Wharton
C
9

To translate in Typscript file ,do follow code

Import in header

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

In constructor declare as

public translate: TranslateService

Suppose the JSON file looks like this

{
    "menu":{
        "Home": "Accueil"
            }
}

Declare the below code in constructor.

Note: Key stands for your main key value that used in language.json file (Here it is "menu")

 this.translate.get('menu').subscribe((data:any)=> {
       console.log(data);
      });
Calling answered 11/6, 2020 at 5:27 Comment(2)
Thank you, it works! also, if you want 'menu.Home' value directly ...you can get it by this.translate.instant('menu.Home'));Pantheas
does it work for nested objects tho? it doesnt for meBranton
R
5

I am using angular 8 > In my case > If you want to translate typescript string into another language then use this > First, make a service file to get translate value, Below is my code for globaltranslate.service.ts file

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

constructor(public translate: TranslateService) {}

Then make a return function........

getTranslation(str) {
    const currentLang = this.translate.currentLang; // get current language
    const returnValue = this.translate.translations[currentLang][str]; // get converted string from current language
    if (returnValue === undefined) {
      return this.translate.translations.en_merch[str]; // if value is getting undefined then return default language string, en_merch is default english language file here
    } else {
      return returnValue;
    }
  }

And in component.ts file, you can import service file and use it like below code...

import {GlobaltranslateService} from '../../../../services/globaltranslate.service';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [GlobaltranslateService]   // add service in provider
})

constructor(
      private gTranslate: GlobaltranslateService // add service into constructor
  ) {}

const title = this.gTranslate.getTranslation('Title text'); // get return value by calling function 'getTranslation' in globaltranslateservice.

This solution is better for all projects of i18n and angular ngx translate

This also works on sweetalert2 strings like below code

Swal (
   this.gTranslate.getTranslation('Warning'),
   data.message,
   'warning'
);

Thanks for reading, If you have any query please message.

Rhearheba answered 22/8, 2019 at 10:19 Comment(2)
What if the translation key has multiple levels like 'USER.PROFILE.NAME' at that time the above code breaksGravure
For that you can use lodash get property which will handle the above case lodash.com/docs/4.17.15#getGravure
D
5

You can use translate.instant() method and pass the key name which is stored in your i18n file. for example:

translate.instant('hello');

and If that's coming from a parameter or variable, directly pass the value.

translate.instant(my.i18n.key);

You can also refer to this ans: https://github.com/ngx-translate/core/issues/835#issuecomment-384188498

Disdain answered 29/11, 2021 at 8:4 Comment(0)
E
3

I don't know if the problem is when this was posted, but assigning the "get" method to a variable in order to get the translated string won't work, as it returns an observable

get should be used like this:

constructor(private translate: TranslateService) { }
   :
   :
this.translate.get ('KEY_TO_TRANSLATE').subscribe (x=> this.translation = x);

To get the string you can use the Instant method:

this.translation = this.translate.instant('KEY_TO_TRANSLATE')

However, this is a synchronous method, so if the translation has not loaded yet, you 'll get the key, not the value. It's all explained in the documentation that can be found in Github.

Episodic answered 18/6, 2021 at 9:45 Comment(0)
W
2

This works for me ( i am using Angular 7). Just import the Translate service on the constructor and then call it from inside myfunction like this :

  getTranslation(){
    let translation = "";
    let clientTranslation = this.translate.get('auth.client').subscribe(cliente =>{
        translation = cliente;
        document.getElementById("clientTest").setAttribute('value', translation);
    }
}

I was using the translation on a form so i pass it to the input with setAttribute, hope this example could help.

Whippletree answered 29/5, 2019 at 21:22 Comment(0)
L
0
errorMessage:string="";
constructor(
    protected translate:TranslateService,
  
  ) {   

}

  ngOnInit(): void {
  
   this.translate.get('PLEASE_ENTER_OTP').subscribe(data=>{
      this.errorMessage=data;
    })
  }

You can subscribe the observable in ngOninit

Leitman answered 31/3, 2021 at 12:48 Comment(0)
A
0

You can use the translate.stream and it will change the value according to the language changes.

constructor(private translate: TranslateService) {
 this.translate
  .stream('my.i18n.key')
  .subscribe((res: string) => {
    console.log(res);
  });
}

Refer https://github.com/ngx-translate/core#methods for more explanation.

Accepter answered 19/5, 2022 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.