Bac*_*tnz 7 internationalization angular
我正在编译我的项目:
ng serve --aot --i18nFile=client/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr
Run Code Online (Sandbox Code Playgroud)
如何在运行时访问区域设置ID?我想根据语言环境显示/隐藏元素.
PS.我确实意识到使用JIT编译我可以简单地这样做:
providers: [ { provide: LOCALE_ID, useValue: 'fr' } ]
Run Code Online (Sandbox Code Playgroud)
但我正在寻找AOT解决方案.我也不想根据主机名或类似的东西来推断语言环境.
Bac*_*tnz 24
只需在构造函数中注入LOCALE_ID,例如
import { LOCALE_ID } from '@angular/core';
...
constructor(
@Inject(LOCALE_ID) public locale: string
) { }
Run Code Online (Sandbox Code Playgroud)
ino*_*nik 19
注入令牌LOCALE_ID 不提供您用户的语言或区域设置,它是静态的并且默认为'en-US'除非您为其提供不同的值 ( docs ):
providers: [{provide: LOCALE_ID, useValue: 'en-GB' }]
Run Code Online (Sandbox Code Playgroud)
这是获取用户首选语言和区域设置的方法:
getUsersLocale(defaultValue: string): string {
if (typeof window === 'undefined' || typeof window.navigator === 'undefined') {
return defaultValue;
}
const wn = window.navigator as any;
let lang = wn.languages ? wn.languages[0] : defaultValue;
lang = lang || wn.language || wn.browserLanguage || wn.userLanguage;
return lang;
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*nko 10
这个问题在谷歌搜索中非常常见,所以我在这里添加另一个解决方案。如果您使用编译时翻译(Angular 的默认值),那么全局
console.log($localize.locale); // statically replaced to its value by Angular compiler
Run Code Online (Sandbox Code Playgroud)
将返回当前区域设置而不涉及依赖注入器等
| 归档时间: |
|
| 查看次数: |
9604 次 |
| 最近记录: |