标签:pre selected 安装 smo from json back htm translate
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>
效果
标签:pre selected 安装 smo from json back htm translate
原文地址:http://www.cnblogs.com/fangshiwei/p/7137857.html