参照 :https://www.cnblogs.com/shcrk/p/9215923.html
angular2的国际化步骤
1、安装ngx所以来的jar包
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2、在app.module模块下导入备注的包
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { WorkComponent } from "./work/work.component";
import { NewsComponent } from "./news/news.component";
//加载语言包过程中,用到http请求
import { HttpClient, HttpClientModule } from "@angular/common/http";
//用于加载i18n文件下的语言包所依赖的加载器
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
//用于国际化模块
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
//读取文件i18n的方法
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}
@NgModule({
declarations: [AppComponent, WorkComponent, NewsComponent],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
//国际化需要的模块 --start TranslateModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient]
}
})
//--end
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
3、配置语言库 在asset下新建 i18n新建语言包
en.json
{ "language000":"Englist",
"language001":"hello world",
"language002":"sex",
"language003":"male",
"language004":"female",
"language005":"username",
"language006":"submit"
}
zh_CN.json
{ "language000":"Englist",
"language001":"hello world",
"language002":"sex",
"language003":"male",
"language004":"female",
"language005":"username",
"language006":"submit"
}
4、在需要用到的component里面注入TranslateService
import { Component, OnInit } from "@angular/core";
//导入TranslateService服务
import { TranslateService } from "@ngx-translate/core";
@Component({
selector: "app-news",
templateUrl: "./news.component.html",
styleUrls: ["./news.component.css"]
})
export class NewsComponent implements OnInit {
public user:string="";
constructor(private translate: TranslateService) {
//增加所支持的语言包
this.translate.addLangs(["en", "zh-CN"]);
//设置默认语言
this.translate.setDefaultLang("zh-CN");
}
ngOnInit() {}
//通过select选择框来改变语言
changeLanguage(lang: string) {
this.translate.use(lang);
}
}
5.html模板
{{"language000"|translate}}:<select #languageSelect (change)="changeLanguage(languageSelect.value)">
<option *ngFor="let language of translate.getLangs()" [value]="language">{{language}}</option>
</select><br>
{{'language005'|translate}}:<textarea [(ngModel)]="user" cols=30 rows=4></textarea>
{{language}}