Loic T Loic T - 4 months ago 126
TypeScript Question

Angular2 i18n language switch

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


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.


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);

Then force reloading, and in i18n.provider.ts

let locale = localStorage.getItem('localeId');