Angular i18 本地化模板中内插字符串的值

问题描述

假设我必须在我的 angular 应用程序 xliff @@field-is-required 中进行翻译,它有一个字符串插值,而 @@lastname一个正常的翻译。

<trans-unit id="field-is-required" datatype="html">
    <source><x id="INTERPOLATION" equiv-text="{{ fieldName }}"/> is required</source>
    <target><x id="INTERPOLATION" equiv-text="{{ fieldName }}"/> ist Pflichtfeld</target>
</trans-unit>
<trans-unit id="lastname" datatype="html">
    <source>Lastname</source>
    <target>Nachname</target>
</trans-unit>

有没有办法在模板中将 @@field-is-required@@lastname 的值结合起来?

我正在想象这样的事情:

<div i18n="@@field-is-required">
    {{ '@@lastname' }} is required
</div>

我尝试了几种组合,但没有任何效果。而且 Angular i18n 的在线文档非常缺乏($localize 甚至没有深入解释)。

解决方法

如果您有一组特定的替代方案,Angular 会建议采用类似的方法

{name,select,lastName {last name} firstName {first name} other {unknwon}} is required

如果姓氏可以是任意字符串,您可以在您的组件中定义它(例如):

const fieldOptions: string[] = [
   $localize`:Last name of a person:Last name`,$localize`:First name of a person:First name`,]
...
let myOption = fieldOptions[0];

最后在 html 中:

<div i18n="@@field-is-required">
    {{myOption}} is required
</div>