11

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

2 回答 2

11

根据ngx-translate 的来源,插值仅适用于字符串:

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.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);
});
于 2017-09-05T07:24:19.807 回答
1

您也可以使用translate管道来执行此操作,以便您可以删除对组件的附加服务依赖项。

<p *ngIf="!item?.isRemovable">
{{'i18n.dashboard.heading' 
| translate:{'TEXTTOFIND': 'STRINGTOREPLACE'} }}
</p>

只需确保您的密钥i18n.test.keyTEXTTOFIND插入即可。像下面的东西。

"heading": "This is with the interpolated {{TEXTTOFIND}} text."

请注意{{}}标题字符串中的 ,并且STRINGTOREPLACE可以是您想要的任何内容。

于 2021-01-29T16:15:57.877 回答