需要安装@ngx-translate/core和@ngx-translate/http-loader这两个插件
在安装之前可以先看看npm上的文档说明>https://www.npmjs.com/package/@ngx-translate/core
其中有个要踩坑的地方非常要注意就是下载对应的angular版本使用,否则会报错,且看下图
image.png
以上是对应的版本要求,那么看看自己用的angular版本,我这里用的是@10.X
image.png
如果直接用 npm install @ngx-translate/core --save来安装,现在会默认安装@9.x,当初就是选择默认的安装,后面有错都很难找。
所以下面我们安装时带一个版本号,因为我用的是angular10,所以这里的版本号应为@13.x的,但是要查到具体版本号,需要差这个插件的更新日志>https://github.com/ngx-translate/core/releases
image.png
打开日志发现最新的为13.0.0,接下来我们开始安装
npm install @ngx-translate/core@13.0.0 --save
接下来我们安装另外一个插件
npm install ngx-translate/http-loader@6.0.0 --save
安装完成之后在入口文件app.moudle.js中进行配置
import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
...
@NgModule({
imports: [
HttpClientModule,//要先注入这个服务不然会报错
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
]
})
在assets中新建翻译文件资源i18n
image.png
要翻译多少种语言这里就新增几个json文件,这里暂时新增了两种
en,json
{
"welcome":"welcome to this app",
"getName":"hello I am {{name}}"
}
zh_cn.json
{
"welcome":"欢迎使用本应用",
"getName":"你好,我是{{name}}"
}
配置好了入口文件后,需要在需要用到的组件中y引入使用
先导入包文件
import { TranslateService } from '@ngx-translate/core';
constructor(private translate: TranslateService) {
translate.setDefaultLang('zh_cn');
}
在页面中使用
<span>{{ "welcome" | translate}}</span>
<button (click)="checkLang('en')">英文</button><button (click)="checkLang('zh_cn')">中文</button>
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
constructor(private translate: TranslateService) {
translate.setDefaultLang('zh_cn');
}
ngOnInit(): void {
}
checkLang(str) {
this.translate.setDefaultLang(str);
}
}
运行之后的页面效果
截图录屏_选择区域_20201014205427.gif