i18n Translate.instant with parameters
Asked Answered
K

1

13

I need to use TranslateService.instant from ngx-core and pass parameters to do string interpolation.
So far I've done:

MY_STRING: "Welcome {{user}}"

In my component I do:

translateService.instant(MY_STRING, {user: 'Nick'})

and what I get from this is:

Welcome {{user}}

The parameter user is not interpolated. What am I doing wrong?

Khanate answered 28/1, 2020 at 11:49 Comment(0)
W
14

For using the instant method, you have to be sure that your translations have been loaded and it is safe to use it, if not it will fail. That may be the point.

The explanation is simple, you have three ways of loading the translation:

  • You are sure that your translation files are already loaded and don't need updates: translate.instant('key')

  • You are not sure about the loading and don't need updates (returns an Observable to subscribe): translate.get('key')

  • You want updates when user is changing the language:
    translate.stream('key')

I think that you might use the get option, as is the one with less known bugs:

let userName = 'Nick'     
translateService.get('MY_STRING', { user: this.userName }).subscribe((text:string) => {console.log(text});
Wilhelmstrasse answered 28/1, 2020 at 12:6 Comment(2)
Hi, thank you, that way it works. The only doubt I have, I am sure that the translation file is already loaded because I trigger the operation manually with a button, and all the other translations in the page area already loaded. Why is that so?Khanate
I am just wondering, maybe it has something to with the key. I always set my keys with double quotes "MY_STRING". Then translateService.instant('MY_STRING', {user: 'Nick'})Wilhelmstrasse

© 2022 - 2024 — McMap. All rights reserved.