Search code examples
angularangular11

Angular 11 (or 9+) I18n set Locale at startup


I have an old angular project (v8) where i have used i18n to tag all my translations. I have 2 xlf files one for en and one for fr - and at runtime choose which file to use. This works fine.

However, in a new angular project (v11) this approach nolonger works. The code doesnt error, and doenst suggest there is a problem, however the text is not tranlsated on screen.

The code in the main.ts file is as follows

let languageCode: string = localStorage.getItem("language") ? localStorage.getItem("language") : 'en-GB';

// use the require method provided by webpack
// we use the webpack raw-loader to return the content as a string
declare const require;

var translations = undefined;

switch (languageCode) {
    case AppService.Languages.english:
        break;
  default:
        translations = require(`raw-loader!./locale/messages.${languageCode}.xlf`);
  break;
}
 
platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translations},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'},
    {provide: LOCALE_ID, useValue: languageCode }
  ]
});

I also have the following in the app.module.ts

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';

let urlParams: URLSearchParams = new URLSearchParams(window.location.search);
let languageCode: string = localStorage.getItem("language") ? localStorage.getItem("language") : 'en-GB';

registerLocaleData(localeFr, 'fr-FR', localeFrExtra);

.....

 providers: [
    { provide: LOCALE_ID, useValue: languageCode },

Has anyone else had experience with this approach not working in newer angular versions?

NOTE: inbuild things like date formatting is coming out in the correct locale - EG date formatting 01 décembre 20. Its purely the i18n replacement that is not being done.


Solution

  • I indeed added extra code, however i now realise that if you use ivy - (tsconfig.json - angularCompilerOptions - "enableIvy": false) then it plainly doesnt work with above code at runtime.

    I have read the ivy documents on the changes they made for i18n and i can see that they just did not intend for translations to be changed at runtime.

    I have switched off ivy and the old code now works.

    I can see their reasoning, but i just cannot have a different url per language so this is my only option.