Angular 7 提供了一个非常强大的国际化与翻译模块,即 @ngx-translate/core
。它可以用来实现多语言支持,并且非常易于使用。下面是一个示例,展示了如何使用 @ngx-translate/core
模块来实现国际化:
@ngx-translate/core
模块:npm install @ngx-translate/core --save
app.module.ts
文件中导入相关模块:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (http: HttpClient) => new TranslateHttpLoader(http, './assets/i18n/', '.json'),
deps: [HttpClient]
}
})
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
i18n
文件夹,并在其中创建一个 en.json
和一个 zh.json
文件。这些文件将包含需要翻译的文本:en.json
文件内容:
{
"hello": "Hello",
"welcome": "Welcome to my app!"
}
zh.json
文件内容:
{
"hello": "你好",
"welcome": "欢迎来到我的应用!"
}
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
template: `
{{ 'hello' | translate }}
{{ 'welcome' | translate }}
`
})
export class AppComponent {
constructor(private translate: TranslateService) {
translate.setDefaultLang('en'); // 设置默认语言为英语
translate.use('en'); // 使用英语翻译
}
}
以上示例演示了如何在 Angular 7 中使用 @ngx-translate/core
模块来实现国际化和翻译。您可以根据自己的需求进行修改和扩展。