Angular2 i18n语言切换 [英] Angular2 i18n language switch

查看:625
本文介绍了Angular2 i18n语言切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来


  • 动态设置要显示的当前语言:我已经遵​​循最新的角食谱关于国际化
    的href =https://angular.io/docs/ts/latest/cookbook/i18n.html =noreferrertitle =here>这里,但它说

  • 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"

如何将用户的语言硬编码为index.html中的全局文档.locale变量这可以在angular2 + typescript中动态设置?

How can this be set dynamically in angular2 + typescript ?

这是我从Angular2 plunkr官方的尝试: https://plnkr.co/edit/lWV4VhzpWYnCXeDBpzsn?p=preview
我已经评论过

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

并尝试检索一个typescript服务中的window.document,并在那里更改区域设置,但尽管它被调用并且正确设置了区域设置(在控制台中看到),界面在启动时不会以选择的语言显示

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);
    location.reload(true);
  }

然后强制重新加载,并在 i18n.provider中。 ts

Then force reloading, and in i18n.provider.ts

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

这篇关于Angular2 i18n语言切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆