效果图:
步骤一. 安装依赖
npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save
@ngx-translate/core包含供翻译的核心程序:TranslateService和一些管道。
@ngx-translate/http-loader从网络服务器加载翻译文件
步骤二. 在app.module.ts中初始化TranslateModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
// ngx-translate and the loader module
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
步骤三. 在app.component.ts组件中设置默认语言
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
}
首先,必须构造函数中注入TranslateService。下一步是设置应用程序的默认语言 translate.setDefaultLang('en')。当然,也可以从用户设置中加载语言。现在,重新加载应用程序会在浏览器控制台中显示错误:
加载资源失败:服务器响应状态为404(未找到)http://localhost:4200/assets/i18n/en.json
这是因为http加载器现在尝试从服务器加载默认语言(en)。
步骤四. 在assets文件夹下新建i18n/en.json和zh.json
{
"app": {
"welcome": "Welcome",
"themeSwitch": "Theme switch",
"languageSwitch": "Language switch",
"chinese": "Chinese"
}
}
{
"app": {
"welcome": "欢迎",
"themeSwitch": "主题切换",
"languageSwitch": "语言切换",
"chinese": "中文"
}
}
步骤五. 在app.component.html中使用 translations
{{ 'app.welcome' | translate }}
步骤六. 在app.component.ts文件中,处理点击事件,实现语言切换
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private translate: TranslateService) {
translate.setDefaultLang('en')
}
language: string;
ngOnInit() {
this.setLanguage();
}
changeLanguage(lan: string) {
const language = localStorage.getItem('lan');
if (lan !== language) {
this.translate.use(lan);
this.saveLanguage(lan);
}
}
saveLanguage(lan: string) {
localStorage.setItem(`lan`, lan);
}
setLanguage() {
this.language = localStorage.getItem('lan') || 'en'
this.translate.use(this.language);
}
}