一. 下载依赖库
npm i @ngx-translate/core
npm i @ngx-translate/http-loader
二. 引入模块
app.module.ts
...
import {TranslateLoader, TranslateModule} from "@ngx-translate/core";
import {TranslateHttpLoader} from "@ngx-translate/http-loader";
export function createTranslateHttpLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/lang/', '.json');
}
const MyModules = [
CoreModule,
ThemeModule,
PagesModule,
];
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
DevUIModule,
FormsModule,
AppRoutingModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateHttpLoader),
deps: [HttpClient]
}
}),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
也可在此处, 获取网页默认语言, 将语言设置为当前网页语言, 还可以在登录后向后端索要用户储存的语言配置信息, 进而切换语言.
三. 创建国际化文件
zh-cn.json
{
"hello"
:
"你好"
,
"name"
:
"张三"
}
en.josn
{
"hello"
:
"hello"
,
"name"
:"Zhang San"
}
四. 使用国际化
<button (click)="click()">点击</button>
<span>{{ 'hello'| translate}}</span>
<span [translate]="'name'">welcome</span>
切换语言在对应 ts 中写:
import {Component, OnInit} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
styleUrls: ['./test1.component.scss']
})
export class Test1Component implements OnInit {
constructor(private translate: TranslateService) {
}
click() {
if (this.translate.currentLang === 'zh-cn')
this.translate.use('en');
else this.translate.use('zh-cn');
}
}