看了其他博主写的文章,总结出来适合angular 10.1.6版本的使用方式,仅供参考
1.下载ngx-translate的依赖库
//^13.0.0
npm install @ngx-translate/core --save
//^6.0.0
npm install @ngx-translate/http-loader --save
2.在app.module.ts中配置,
import { BrowserModule } from '@angular/platform-browser';
import { Inject, LOCALE_ID, NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { environment } from "../environments/environment";
import { TranslateModule, TranslateLoader,
TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule ,HttpClient} from '@angular/common/http';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
export function TranslateLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}
export function LocaleIdFactory() {
return "zh-CN";
}
3.在imports中申明并在constructor函数中设置
@NgModule({
declarations: [
AppComponent,
],
imports: [
AppRoutingModule,
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: TranslateLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [
{
provide: LOCALE_ID,
useFactory: LocaleIdFactory
},
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private i18n: TranslateService, @Inject(LOCALE_ID) locale: string) {
if (environment.supportedLocale.indexOf(locale) === -1) {
locale = "vi";
}
this.i18n.use(locale);
}
}
4.在envirronments文件中分别配置开发环境和生产环境的语言支持
// environment.prod.ts
export const environment = {
production: true,
supportedLocale:['en-US','zh-CN','id','vn'],
};
//environment.ts
export const environment = {
production: false,
supportedLocale:['en-US','zh-CN','id','vi'],
};
5.配置语言json文件( assets/i18n/en-US.json 和 assets/i18n/zh-CN.json)
// en-US.json
{
"app.welcome": "welcome11",
"captcha.send": "Resend{{count}}"
}
//zh-CN.json
{
"app.welcome": "欢迎",
"captcha.send": "重新发送{{count}}"
}
6.使用方式(普通-带参数-翻译命令-js方法获取-切换当前语言等)
<!-- 翻译 -->
<p>{{ 'app.welcome' | translate }}</p>
<!-- 翻译管道 -->
<p>{{'captcha.send' | translate: {count:"12"} }}</p>
<!-- 翻译指令 -->
<p translate="captcha.send" [translateParams]="obj"></p>
<button (click)="change()">en/cn</button>
import { Component } from '@angular/core';
import { TranslateService } from "@ngx-translate/core";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
constructor( private i18n: TranslateService,){
// 翻译服务
this.i18n.get('app.welcome').subscribe((res:string)=>{
console.log(res);
});
}
title = 'translation';
obj = {
count:1222
}
change(){
if(this.i18n.defaultLang == 'zh-CN'){
this.i18n.use('en-US');
this.i18n.defaultLang = 'en-US';
} else {
this.i18n.use('zh-CN');
this.i18n.defaultLang = 'zh-CN';
}
}
}