Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use angular 9 $localize with plurals?

Since Angular 9 we can use

$localize`Hello ${name}:name:`

For i18n in typescript code. This still has some limitations as the ng xi18n command does not detect the strings, but if these texts are added manually to the translation file it works.

The $localize function is quite well documented in the JSDoc in the source, however it does not explain how to work with plurals. What I mean is something like this (pseudo-code):

$localize`Hello {${count}, plural, =1 {reader} other {readers}}`

Is this possible with $localize? If yes: How? If no: How does Angular compile such expressions from HTML to TypeScript?

like image 514
yankee Avatar asked Mar 09 '20 08:03

yankee


People also ask

What is internalization in angular?

Angular Internationalizationlink Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales.

What is angular localize init?

@angular/localize/initlinkThe @angular/localize package exposes the $localize function in the global namespace, which can be used to tag i18n messages in your code that needs to be translated.


2 Answers

For now, it is not possible to use ICUs with $localize, as discussed in this github issue. From the last comments, it looks like angular team is considering it if it remains lightweight.

Meanwhile, the suggested workaround is to create your own helper method that returns the correct translation based on the count parameter.

    title = $localize `Hi ${this.name}! You have ${
        plural(this.users.length. {
          0: $localize `no users`,
          1: $localize `one user`,
          other: $localize`${this.users.length} users`,
    }.`

    function plural(value, options) {
      // Handle 0, 1, ... cases
      const directResult = options[value];
      if (directResult !== undefined) { return directResult; }
      // handle zero, one, two, few, many
      // ...
      return options.other;
    } 
like image 186
David Avatar answered Sep 21 '22 11:09

David


I've just read issue https://github.com/angular/angular/issues/35912 and I think that intl-messageformat can do what you need.

See https://github.com/formatjs/formatjs/tree/master/packages/intl-messageformat.

like image 24
kemsky Avatar answered Sep 18 '22 11:09

kemsky