1.安装依赖
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2.引入模块
在app.module.ts中引入
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient);
}
@ngmodule导入
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
]
3.添加多语言文件
assets/i18n/en.json
{"welcome":"WELCOME"}
assets/i18n/zh.json
{"welcome":"欢迎"}
4.初始化语言
在app.component.ts添加语言初始化,默认为浏览器语言
import { TranslateService } from '@ngx-translate/core';
constructor(public translate: TranslateService) {
translate.addLangs(["zh", "en"]);
translate.setDefaultLang('zh');
const browserLang = translate.getBrowserLang();
//修改语言
translate.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
}
5.使用
{{”welcome“|translate}}