首页 > 代码库 > Angular 2/4 多语言 国际化支持
Angular 2/4 多语言 国际化支持
npm @ngx-translate/core --save npm @ngx-translate/http-loader
2. app.module.ts
import { BrowserModule } from ‘@angular/platform-browser‘; import { NgModule } from ‘@angular/core‘; import { FormsModule } from ‘@angular/forms‘; import { HttpModule, Http } from ‘@angular/http‘; import { TranslateModule, TranslateLoader } from ‘@ngx-translate/core‘; import { TranslateHttpLoader } from ‘@ngx-translate/http-loader‘; import { AppComponent } from ‘./app.component‘; export function createTranslateLoader(http: Http) { return new TranslateHttpLoader(http, ‘./assets/i18n/‘, ‘.json‘); } @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [Http] } }), FormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
加载TranslateModule的loader, parser 或者missing translations handler
TranslateModule.forRoot();
默认的http loader
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
}),
实现AOT编译
export function createTranslateLoader(http: Http) { return new TranslateHttpLoader(http, ‘./assets/i18n/‘, ‘.json‘); }
TranslateHttpLoader 加载 "/assets/i18n/[lang].json" 文件, [lang] 为语言文件名
初始化 TranslateService
import { Component } from ‘@angular/core‘; import { TranslateService } from ‘@ngx-translate/core‘; @Component({ selector: ‘app-root‘, templateUrl: ‘./app.component.html‘, styleUrls: [‘./app.component.css‘] }) export class AppComponent { constructor(public translate: TranslateService) { // this language will be used as a fallback when a translation isn‘t found in the current language translate.addLangs(["en", "ch"]); let browserLang = translate.getBrowserLang(); console.log("browser languague: " + browserLang); translate.use(browserLang.match(/en|ch/) ? browserLang : ‘en‘); } }
语言文件 /assets/i18n/ch.json
{ "HOME": { "TITLE": "你好, Angular ngx-translate!", "SELECT": "更改语言" } }
/assets/i18n/en.json
{ "HOME": { "TITLE": "Hello Angular with ngx-translate!", "SELECT": "Change language" } }
app.component.html 文件
<div> <h2>{{ ‘HOME.TITLE‘ | translate }}</h2> <label> {{ ‘HOME.SELECT‘ | translate }} <select #langSelect (change)="translate.use(langSelect.value)"> <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option> </select> </label> </div>
效果
Angular 2/4 多语言 国际化支持
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。