I am using the instant method from ngx-translate to translate some messages into the language of the user. These messages are passed as JSON to ngx-translate. Some of the messages take dynamic values:
{
"message.key": "First value is {{0}} and second value is {{1}}",
"message.key2": "Value is {{0}}"
}
To get the translated text with the interpolated dynamic values, I use the instant method like this
messageText = this.translateService.instant('message.key2', {0: 'Value to be interpolated'});
The problem is that I get these values in a string array params: string[]
. So I need to transform the string array into an Object that looks like {0:params[0], 1:params[1]}
I know that I could use a construct like
myTranslationMethod(messageKey: string, params: string[]): string {
let paramsAsObject;
if (params.length === 1) {
paramsAsObject = {
0: params[0]
}
} else {
paramsAsObject = {
0: params[0],
1: params[1]
}
}
messageText = this.translateService.instant(messageKey,paramsAsObject);
return messageText;
}
However, I would need to extend the if construct if a message with three or more parameters is added to the application. So I want to implement it in a generic way, where I don't need to change the code if a message with more parameters is used.
Is there a way to create paramsAsObject independent of the length of params or to use the array directly with ngx-translate?
Thank you for your input.