Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

angular - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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} }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...