20

I'm looking for a way to

  • set dynamically the current language to be displayed: I have followed the latest angular cookbook here about internationalization but it says "the user's language is hardcoded as a global document.locale variable in the index.html"

How can this be set dynamically in angular2 + typescript ?

Here is my attempt from the official Angular2 plunkr : https://plnkr.co/edit/lWV4VhzpWYnCXeDBpzsn?p=preview where I've commented out the

document.locale='en';

and tried to retrieve the window.document inside a typescript service, and change the locale there, but despite it is called and the locale set properly (seen in the console), the interface is not displayed in the chosen language at startup.

Then of course the dropdown buttons don't work either because the same erroneous way is used and the display is not refreshed but that is the next step.

Loic T
  • 233
  • 1
  • 2
  • 8
  • In the meantime I have done a version which reads document.URL and sets the document.locale inside the i18n-providers.ts file. It's certainly not the right way to proceed but in the meantime I can carry on the translations stuff https://plnkr.co/edit/TE7raLGC9pvYfaRu6Syg?p=preview (This example does not work due on plunkr, but works locally) – Loic T Oct 10 '16 at 09:28

1 Answers1

21

I am saving user selected language key into local storage:

//<select name="selectLocate" (change)="onChange($event.target.value)">
 public onChange(localeId: string): void {
    localStorage.setItem('localeId', localeId);
    location.reload(true);
  }

Then force reloading, and in i18n.provider.ts

let locale = localStorage.getItem('localeId');
Bahodir
  • 539
  • 1
  • 9
  • 29
  • 1
    simple and great. I have changed the plunkr example and it works fine! https://plnkr.co/edit/JyE4l4TjEruuPsrbanmK – Loic T Nov 03 '16 at 14:58
  • 1
    I am not using systemsjs. Is it possible to configure it using webpack ? – Coder Guru Jan 05 '17 at 18:01
  • @sardarCoder Don't know if you are still struggling with this, but if so. Yes you can: Just use the raw-loader to load xlf-files: `{test: /\.xlf/, loader: 'raw-loader'},` – Tienou Feb 17 '17 at 09:08
  • @GOB raw-loader is a loader for webpack that lets you import files as a string. So? – titusfx Oct 31 '17 at 17:45
  • 1
    What if I get settings on an app load and it contains the language I should use? I need the way to apply it wothout a page reload (don't want to get settings twice). – Makarov Sergey Nov 03 '17 at 07:07
  • hi guys i have some error like this Argument of type '{ providers: Object[]; }' is not assignable to parameter of type '(CompilerOptions & BootstrapOptions) | (CompilerOptions & BootstrapOptions)[]'. Type '{ providers: Object[]; }' is not assignable to type '(CompilerOptions & BootstrapOptions)[]'. Property 'includes' is missing in type '{ providers: Object[]; }' can u tel me how can i fix this error my guide is plnkr.co/edit/JyE4l4TjEruuPsrbanmK – mohammad mahmoodi Aug 30 '18 at 16:44