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

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

问题描述

我正在寻找方法

  • 动态设置当前要显示的语言:我已经按照最新的 Angular 食谱 这里 关于国际化但它说用户的语言被硬编码为 index.html 中的全局 document.locale 变量"
  • 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"

如何在 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天全站免登陆