Ngx-translate Package Use
1. Installation
NPM @ngx-translate/core--savenpm @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), DEP S: [Http]}}), Formsmodule, HttpModule], providers: [], Bootstrap: [AppComponent]}) Expor T class Appmodule {}
Load Translatemodule loader, parser or missing translations handler
Translatemodule.forroot ();
The default HTTP Loader
Translatemodule.forroot ({ loader: { provide:translateloader, usefactory: (Createtranslateloader), deps: [Http] } }),
Implementing AOT Compilation
function Createtranslateloader (http:http) { returnnew translatehttploader (HTTP, './assets/ i18n/', '. JSON ');}
Translatehttploader loading "/assets/i18n/[lang].json" file, [lang] for language file name
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 is used as a fallback when a translation is ' t found in the current languageTranslate.addlangs (["en", "ch"]); Let Browserlang=Translate.getbrowserlang (); Console.log ("Browser Languague:" +Browserlang); Translate.use (Browserlang.match (/en|ch/)? Browserlang: ' En '); }}
Language file/assets/i18n/ch.json
{ "HOME": { "TITLE": "Hello, Angular ngx-translate!" , " Select ":" Change Language " }}
/assets/i18n/en.json
{ "HOME": { "TITLE": "Hello Angular with ngx-translate!" , " Select ":" Change Language " }}
app.component.html file
<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>
Effect
Angular 2/4 Multi-lingual internationalization support