1.npm 安装 ngx-translate 模块
npm install@ngx-translate/core--save
npm install@ngx-translate/http-loader--save
2.开始配置
在app.module.ts 中添加:
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
imports: [
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
],
官网写的的是引入 import { HttpModule, Http } from '@angular/http';
但是新版的angluar中, httpclient逐渐替换http了。所以我这里引入的是HttpClient。下面的imports中,也要对应起来。
在app.component.ts中添加:
import { TranslateService } from '@ngx-translate/core';
constructor(
public translate: TranslateService
) {
translate.setDefaultLang('en');
}
在assets目录下新建 "i18n"文件夹,并增加"en.json"、"zh.json"
imageen.json如下:
{
"HOME": {
"TITLE":"Home",
"CONTENT":"Welcome to my app!"
}
}
zh.json如下:
{
"HOME": {
"TITLE":"首页",
"CONTENT":"欢迎来到我的应用!"
}
}
3.运用
在home.html中:
<ion-navbar>
<ion-title>{{ 'HOME.TITLE' | translate }}</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button (click)="changeLanguage()" ion-button color="light">设置语言</button>
<h2>{{ 'HOME.CONTENT' | translate }}</h2>
</ion-content>
在home.ts中:
import { NavController, AlertController } from 'ionic-angular';
import { TranslateService } from '@ngx-translate/core';
RadioOpen: boolean;
RadioResult;
langs;
constructor(private navCtrl: NavController,
public alerCtrl: AlertController,
public translate: TranslateService
) {
}
changeLanguage() {
this.langs = [{ language: "English", type: "en" }, { language: "简体中文", type: "zh" }]
let alert = this.alerCtrl.create();
alert.setTitle('语言选择');
for (let lang of this.langs) {
alert.addInput({
type: 'radio',
label: lang["language"],
value: lang["type"],
checked: (lang["type"] == this.translate.getDefaultLang() ? true : false)
});
}
alert.addButton('取消');
alert.addButton({
text: '确认',
handler: data => {
this.RadioOpen = false;
this.RadioResult = data;
this.translate.setDefaultLang(data);
this.translate.use(data);
}
});
alert.present().then(() => {
this.RadioOpen = true;
});
}
到此,就可以实现了,如下图:
image.png
================================ 更新下 ==============================================
【 https://www.jianshu.com/p/d64d2917d0db 这篇是关于怎么在ts里面实现中英文转换的 】
网友评论