angularinternationalization

Using angular i18n inside *ngFor loop with angular 5


I would like to use dynamic translations inside a ngFor-Loop in template like this:

<mat-card *ngFor="let user of usersList">
    <mat-card-title>
        <span>{{user.name}}</span>
    </mat-card-title>
    <mat-card-content>
        <!--This is the enum i would like to translate dynamic -->
        <span i18n="Role@@role">{{user.role}}</span>
    </mat-card-content>
</mat-card>

Is there a way with the current on-board tools of angular 5 i18e (internationalization) to dynamically translate this enum value?

As I read, in Angular 6.1 or later there will be a way to translate values in .ts. But what, if i would like to use this for now? Any workarounds?

To use alternative text messages could't be a good way, because what if you habe hundred of values in the enum. I would'n repeat my enum in the html code.


Solution

  • I managed to make it work. Here is my example using format xlif2 with a select ICU expression

    https://angular.io/guide/i18n#translate-select

    Here is how I translated the select

    component.html

        <ul>
          <li *ngFor="let user of users">
            <span i18n="@@role">dummy {user.role, select, admin {admin}}</span>
          </li>
          </ul>
    

    Note:

    • I needed to add some text before the ICU expression (dummy) otherwise it did not work.
    • Assign an id to the translation (here it's role)
    • You do not need to have all possible values defined here . For instance, I just defined one (admin) to have a valid ICU expression. All other possible values will just be in the translation files

    Then extract the message file (e.g. for french)

        ng xi18n --outputPath src/locale --locale fr--i18nFormat=xlf2 --outFile messages.fr.xlf
    

    Then set the translations in the message messages.[language].xlf file

        <unit id="role">
          <segment>
            <source>ROLE <ph id="0" equiv="ICU" disp="{user.role, select, admin {...} user {...} other {...}}"/></source>
            <target>ROLE <ph id="0" equiv="ICU" disp="{user.role, select, admin {...} user {...} other {...}}"/></target>
          </segment>
        </unit>
        <unit id="7222321253551421654">
          <segment>
            <source>{VAR_SELECT, select, admin {administrator} user {user} other {other} }</source>
            <target>{VAR_SELECT, select, admin {administrateur} user {utilisateur} other {autre} }</target>
          </segment>
        </unit>
    

    The ID of the unit 7222321253551421654 containing the actual values to translate is the one generated by the tool. You just need to modify that unit to add as many roles/translations as you want