Angular 2 i18n dynamic/instant translation

2020-02-01 04:13发布

问题:

I've followed the angular.io cookbook for internationalization (https://angular.io/docs/ts/latest/cookbook/i18n.html#!#angular-i18n). Everything works fine, and if I change my locale in the index.html file:

document.locale = 'en';

But I wish to change this dynamically, as we used to do in AngularJS. I have found several solutions, such as this:

//mycomponent.component.ts
changeLang(){
localStorage.setItem('localeId', "es");
location.reload(true);

} //I hardcoded the locale, but you get the idea

Is there a way to translate the document on the go? Because this solution is not practical, and has a long reload time. Thank you for your help!

回答1:

In short it is not possible to change the locale without reloading the app as the translation work is done by Angular compiler.


As of today you have two options when using official Angular i18n:

Use AOT compiler

In this case a separate bundle will be created for every locale and you'll have to swap the whole application, i.e. reload it.

When you internationalize with the AOT compiler, you must pre-build a separate application package for each language and serve the appropriate package based on either server-side language detection or url parameters.

Use JIT compiler

This approach is less performant but you'll not necessarily need a bundle per language.
In this case you load your translation file with webpack and provide it to Angular compiler during bootstrap.

The JIT compiler compiles the app in the browser as the app loads. Translation with the JIT compiler is a dynamic process of:

  • Importing the appropriate language translation file as a string constant.
  • Creating corresponding translation providers for the JIT compiler.
  • Bootstrapping the app with those providers.

Although in the official documentation they only have examples with useValue providers, I'm pretty sure you can use useFactory to provide TRANSLATIONS and LOCALE_ID based on your configuration.
You'll still have to re-bootstrap your app upon language change, which, in turn, means reloading, but hey, the user have this bundle cached in the browser, so the reload should be pretty fast.


Anyways, as of now, if you want to get really dynamic translations I'd suggest you to use ngx-translate.
Besides translate pipe and service they have this nice speculative polyfill that might save you some headache when code translations will be supported officially by Angular i18n.



回答2:

You can certainly do this if you're using JIT compilation. You'll need a factory provider for your translations. Add something like this to your root module:

  export function localeFactory(): string {
    return (window.clientInformation && window.clientInformation.language) || window.navigator.language;
  }

  providers:
  [
    {
      provide: TRANSLATIONS,
      useFactory: (locale) => {
        locale = locale || 'en'; // default to english if no locale provided
        return require(`raw-loader!../locale/messages.${locale}.xlf`);
      },
      deps: [LOCALE_ID]
    },
    {
      provide: LOCALE_ID,
      useFactory: localeFactory
    },
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'},


回答3:

You can check that out, for me it works flawlessly and has great performance (instant translation with no loading time nor reload) :

https://github.com/ocombe/ng2-translate

You can then use a local storage or anything with that to set the language :

translateService.use(window.localStorage.getItem('language'));

You can set your translations in a single file, and you can order the translations in JSON format : (I encapsulate one object per component)

"PASSWORD_CONFIRM": {
    "TITLE": "Merci !",
    "DESCRIPTION": "Votre nouveau mot de passe a bien été enregistré. Vous pouvez désormais accéder à la plateforme !",
    "BUTTON": "Entrer sur la plateforme"
  },
  ...

and then you can set your text in your HTML as follow :

  <div class="title">{{'PASSWORD_CONFIRM.TITLE' | translate}}</div>
  <div class="description">
      {{'PASSWORD_CONFIRM.DESCRIPTION' | translate}}
  </div>