Angular2 i18n language switch

不打扰是莪最后的温柔 提交于 2019-11-29 06:13:04

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39894394/angular2-i18n-language-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!