Search code examples
angularinternationalizationangular-i18n

Angular i18 localize value of interpolated string in template


Let's say I have to translations in my angular app xliff @@field-is-required which has a string interpolation and @@lastname which is a normal translation.

<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>

Is there any way to combine @@field-is-required with the value of @@lastname in a template?

I'm imagining something like:

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

I've tried a few combination but nothing worked for me. And the online documentation of Angular i18n is very lacking ($localize isn't even explained in depth).


Solution

  • If you have a certain set of alternates, Angular suggests an approach like

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

    If the last name can be an arbitrary string, you can define it in your component (for example):

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

    and finally in the html:

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