ngx-translate with dynamic text on ts file

半城伤御伤魂 提交于 2019-12-19 02:51:09

问题


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?


回答1:


You have to inject the Translate Service in your component :

constructor(private translate: TranslateService) {}

And make a call to it, it will return an observable :

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

In your translation file you have to declare something like this :

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

UPDATE

As @Exari Constantin said, you can also use the instant method of the TranslateService to programmatically translate a key. It will look like this :

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



回答2:


You also can do it by this way:

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


来源:https://stackoverflow.com/questions/46155989/ngx-translate-with-dynamic-text-on-ts-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!