Introduction Ngx-translate is Angular's international (i18n) library, and the address on GitHub is the arrow https://github.com/ngx-translate/core
Use the ngx-translate with the IONIC2 project to implement multi-language switching.
1. Installing Ng2-translate
At the command prompt, enter the following carriage return under project directory.
NPM Install Ng2-translate--save
2. Import Translatemodule
First Import Translatemodule
Add the following code under App.module.ts
Import {HttpModule, Http} from ' @angular/http '; import {translatemodule, Translateloader, translatestaticloader} from ' Ng2-translate '; Export function Createtranslateloader (http:http) { return new Translatestaticloader (HTTP, './ assets/i18n ', '. json ');} @NgModule ({ imports: [ browsermodule, translatemodule.forroot ({ provide:translateloader, Usefactory: (Createtranslateloader), deps: [Http] }), ionicmodule.forroot (MYAPP) ]})
Circled is the added code.
3. Add a Language pack
Under Src/assets, create a new folder i18n, add En.json under the i18n folder, and Tw.json,zh.json the three JSON files.
and add content
En.json
{" home": { "TITLE": "Home", "CONTENT": "Hello word!" }}
Tw.json
{" HOME": { "TITLE": "homepage", "CONTENT": Hello, world! " }}
Zh.json
{" home": { "TITLE": "Home", "CONTENT": Hello, world! " }}
3. Usage
Open file App.component.ts, add code
Set the default language pack
and import
Import {Translateservice} from ' Ng2-translate ';
In the page, this uses
Home.html
<Ion-header> <Ion-navbar> <Ion-title>{' HOME '. TITLE ' | Translate}}</Ion-title> </Ion-navbar></Ion-header><ion-contentpadding> <Button(click)= "Changelanguage ()"Ion-button Color= "Light">Set Language</Button> <H2>{' HOME '. CONTENT ' | Translate}}</H2></ion-content>
Home.ts
Import {Component} from ' @angular/core '; import {navcontroller, alertcontroller} from ' ionic-angular '; import {Translat EService} from ' Ng2-translate '; @Component ({selector: ' Page-home ', Templateurl: ' home.html '}) Export class Homepage {R Adioopen:boolean; Radioresult; Langs: [{}]; Constructor (public navctrl:navcontroller, public alerctrl:alertcontroller, public translate:translateservice) {} Cha Ngelanguage () {this.langs = [{language: "中文版", type: "en"}, {language: "Chinese Simplified", type: "zh"}, {language: "Traditional Chinese" , type: "TW"}] let alert = this.alerCtrl.create (); Alert.settitle (' language selection '); For (Let Lang of This.langs) {alert.addinput ({type: ' Radio ', label:lang["language"], value:l ang["type"], checked: (lang["type"] = = This.translate.getDefaultLang ()? true:false)}); } Alert.addbutton (' Cancel '); Alert.addbutton ({text: ' confirm ', Handler:data = = {this. Radioopen = false; This. Radioresult = dAta This.translate.setDefaultLang (data); This.translate.use (data); } }); Alert.present (). then (() = {this. Radioopen = true; }); }}
Results:
Ionic2-based Ngx-translate for multi-language switching, translation