在Angular中使用多語言 ngx-translate
安裝
ngx-translate
npm install @ngx-translate/core --save
導(dǎo)入
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 { }
-
配置 - 默認(rèn)情況下,沒有可用的加載語言配置的程序吠冤。可以使用
TranslateService
提供的setTranslation
方法手動設(shè)置,但是最好使用加載器, 可以使用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 ? [可選] 默認(rèn)是 assets/i18n/
// suffix ? [可選] 默認(rèn)是 .json
return new TranslateHttpLoader(http,'./assets/i18n/','.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
// 設(shè)置默認(rèn)的語言
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"
}
}