学习自:https://blog.csdn.net/qq_36671474/article/details/100042765
下载安装依赖
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader
folder图 ( 代码涉及一下文件 - 更改 / 新增 )
app.component.html
<h1>
<span> test the i18n module: ngx-translate</span>
<h1>{{ 'hello' | translate }}</h1>
</h1>
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 {
title = 'myNGdemo1';
//新增
constructor(public translateService: TranslateService) {}
//新增
ngOnInit(): void {
this.translateService.addLangs(["zh","en"]);
this.translateService.setDefaultLang("en");
const browserLang = this.translateService.getBrowserLang();
this.translateService.use(browserLang?.match('/zh|/en') ? browserLang : 'zh');
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
//新增
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
//新增
export function TranslateLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
//新增
HttpClientModule,
TranslateModule.forRoot({
loader: [{
provide: TranslateLoader,
useFactory: (TranslateLoaderFactory),
deps: [HttpClient]
}]
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
assets/i18n
/en.json
{
"hello": "the word is hello"
}
/zh.json
{
"hello": "你好"
}
environment
export const environment: any = {
production: true,
supportedLocale: ["en-US", "zh-CN", "id", "vi"],
};