在Angular中使用多语言 ngx-translate
-
安装
ngx-translate
npm install @ngx-translate/core --save
-
导入
TranslateModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
TranslateModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-
配置 - 默认情况下,没有可用的加载语言配置的程序。可以使用
TranslateService
提供的setTranslation
方法手动设置,但是最好使用加载器, 可以使用TranslateHttpLoader
加载器,他会通过HttpClient
请求文件加载翻译。
安装@ngx-translate/http-loader
npm install @ngx-translate/http-loader --save
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { AppComponent } from './app.component';
// AoT requires an exported function for factories
export function HttpLoaderFactory(http: HttpClient) {
// http: HttpClient, prefix?: string, suffix?: string
// prefix ? [可选] 默认是 assets/i18n/
// suffix ? [可选] 默认是 .json
return new TranslateHttpLoader(http,'./assets/i18n/','.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
// 设置默认的语言
defaultLanguage: 'zh-cn'
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-
使用 -
translate
的几种使用方法 管道 & 指令
<div>
<!-- 管道 -->
<h1 [title]="'UI.title' | translate">{{'UI.title' | translate}}</h1>
<p>{{ 'UI.greeting' | translate:{'name':'Angular'} }}</p>
<!-- 指令 -->
<p translate>UI.description</p>
<p [translate]="'UI.greeting'" [translateParams]="{name: 'Angular'}"></p>
<p translate [translateParams]="{name: 'Angular'}">UI.greeting</p>
</div>
-
切换语言 -
TranslateService
提供了use
方法, 支持切换
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
template: `
<div>
<!-- 管道 -->
<h1 [title]="'UI.title' | translate">{{'UI.title' | translate}}</h1>
<p>{{ 'UI.greeting' | translate:{'name':'Angular'} }}</p>
<!-- 指令 -->
<p translate>UI.description</p>
<p [translate]="'UI.greeting'" [translateParams]="{name: 'Angular'}"></p>
<p translate [translateParams]="{name: 'Angular'}">UI.greeting</p>
</div>
<button (click)="changeLanguage('en')">en</button>
<button (click)="changeLanguage('zh-cn')">zh-cn</button>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
public constructor(
private translate: TranslateService
) { }
// 切换语言
public changeLanguage(language: string) {
this.translate.use(language);
}
}
-
json
文件配置
在src/assets/i18n/
下
// zh-cn.json
{
"UI": {
"title": "示例",
"greeting": "你好 {{name}}",
"description": "中文"
}
}
// en.json
{
"UI": {
"title": "DEMO",
"greeting": "hello {{name}}",
"description": "en"
}
}
网友评论