前言
本文将介绍在 Angular4 项目中配置 ngx-translate i18n 国际化组件的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:
npm 安装 ngx-translate 模块
在 Angular 项目配置
app.module.ts
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,useFactory: (createTranslateHttpLoader),deps: [Http]
}
})
]
结果如下:
import { AppComponent } from './app.component';
export function createTranslateHttpLoader(http: Http) {
return new TranslateHttpLoader(http,'./assets/i18n/','.json');
}
@NgModule({
declarations: [
AppComponent
],imports: [
browserModule,HttpModule,TranslateModule.forRoot({
loader: {
provide: TranslateLoader,deps: [Http]
}
})
],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
constructor(public translateService: TranslateService) {
}
ngOnInit() {
// --- set i18n begin ---
this.translateService.addLangs(["zh","en"]);
this.translateService.setDefaultLang("zh");
const browserLang = this.translateService.getbrowserLang();
this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
// --- set i18n end ---
}
结果如下:
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(public translateService: TranslateService) {
}
ngOnInit() {
// --- set i18n begin ---
this.translateService.addLangs(["zh","en"]);
this.translateService.setDefaultLang("zh");
const browserLang = this.translateService.getbrowserLang();
this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
// --- set i18n end ---
}
}
添加多语言文件
在 src/app/assets/ 下创建 i18n 文件夹,并在文件夹内创建 en.json 和 zh.json 文件
测试
app.component.html
{{ 'hello' | translate }}
在 en.json 和 zh.json 文件中添加配置
en.json
zh.json
测试结果
在中文下
示例代码
参考文章
nofollow" target="_blank" href="https://github.com/ngx-translate/core">ngx-translate core
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对编程之家的支持。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。