效果图:
步骤一. 安装依赖
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
<span>{{'app.welcome' | translate}}</span>
步骤六. 在 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);
}
}