Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular translate service, interpolate params in nested json

In angular translation service, interpolating params in normal translation json works well. But in nested json, interpolating params is not working.

My JSON:

  "SampleField": {
    "SampleValidation": {
      "MIN": "Value should not be less than {{min}}", 
      "MAX": "Value should not be more than {{max}}", 
    }
  }

My Angular Code:

ngOnInit(): void {
  this.translateService.get('SampleField.Validation', {
    // using hard coded value just as a sample
    min: 0, max: 2000
  }).subscribe(translation => {
    console.log(translation);
  });
}

Expected Output:

{
    MIN: "Value should not be less than 0",
    MAX: "Value should not be greater than 2000"
}

Actual Output:

{
    MIN: "Value should not be less than {{min}}",
    MAX: "Value should not be greater than {{max}}"
}
like image 862
Syed Aqeel Ashiq Avatar asked Sep 03 '17 16:09

Syed Aqeel Ashiq


1 Answers

According to the source of ngx-translate interpolation works only on strings:

export abstract class TranslateParser {
/**
 * Interpolates a string to replace parameters
 * "This is a {{ key }}" ==> "This is a value", with params = { key: "value" }
 * @param expr
 * @param params
 * @returns {string}
 */
abstract interpolate(expr: string | Function, params?: any): string;

This means you might need to use an array of keys instead of a non-leaf element:

this.translateService.get([
    'SampleField.Validation.MIN', 
    'SampleField.Validation.MAX'
  ], {
  // using hard coded value just as a sample
  min: 0, max: 2000
}).subscribe(translation => {
  console.log(translation);
});
like image 183
Istvan Avatar answered Sep 25 '22 03:09

Istvan