Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-translate with dynamic text on ts file

I'm using ngx-translate for internationalization on Ionic 3 app. I have used pipe nicely on HTML code. But now I have a situation like below on ts file. Can you tell me how to handle such dynamic use case with ngx?

 updateApi(topic) {
     this.showToast(`Topic ${topic.name} subscribed!`);//this is the dynamic text
  }

 showToast(message) {
        let toast = this.toastCtrl.create({
            message: message,
            duration: 3000
        });
        toast.present();
    }

The problem here is I don't know the value of ${topic.name} up front. So how can I give the key/value for that on i18n json file? or am I missing something here?

like image 444
Sampath Avatar asked Sep 11 '17 12:09

Sampath


People also ask

How do I translate words into components TS files?

component. ts file we need to import a translate service from @ngx-translate/core package inject the service in constructor and use it after changing the language. Now create a folder inside assets, name it 'translate,' inside of it create a json file.


2 Answers

You have to inject the Translate Service in your component :

constructor(private translate: TranslateService) {}

And declare in your translation file something like this :

{
  "TOPIC": "Topic {{value}} subscribed!"
}

Then you can choose one of the following way :

Translate instantly :

showToast(this.translate.instant('TOPIC', {value: topic.name}));

Translate with an observable

this.translate.get('TOPIC', {value: topic.name}).subscribe(res => {
      showToast(res);
});

Translate directly in the template

{{ 'TOPIC' | translate: {value: topic.name} }}
like image 120
Enima Avatar answered Sep 20 '22 09:09

Enima


You also can do it by this way:

this.showToast(this.translate.instant('TOPIC', {value: ${topic.name}}));
like image 22
Exari Constantin Avatar answered Sep 18 '22 09:09

Exari Constantin