dilluns, 3 d’abril del 2017

Ionic 2, localizing with NG2-translate

It's time to localize your app, for this in Ionic 2 you can use the NG2-translate library. Here you can find more info.
The first step is to install the library, for this in a terminal into your project directory run

   npm install ng2-translate --save

Next it must be imported in the NgModule of the app and added to the imports array. The code in the app.module.ts file  would be like this


   import { NgModule, ErrorHandler } from '@angular/core';
   import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
   import { Http } from '@angular/http'; 
   import { TranslateModule, 
            TranslateLoader, 
            TranslateStaticLoader } from 'ng2-translate/ng2-translate'

   export function createTranslateLoader(http: Http) {
      return new TranslateStaticLoader(http, 'assets/i18n', '.json');
   }

   @NgModule({
      declarations: [
         MyApp
      ],
      imports: [
         IonicModule.forRoot(MyApp),
         TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [Http]
         })
      ],
      bootstrap: [IonicApp],
      entryComponents: [
         MyApp
      ],
      providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
   })
   export class AppModule {}

The function createTranslateLoader(http: Http) change the default location of the json translation files. By default it is in i18n/ and for Ionic 2 must be change to src/assets and we added it in the imports array. How createTranslateLoader(http: Http) uses Http we import it from @angular/http.

Now in the src/assets/i18n directory we create a file for each language what we want translate en.json, ca.json, fr.json, es.json, etc...

The json file for catalan looks like

   {
    "TAXES": "Impostos",
    "JANUARY": "Gener",
    "FEBRUARY": "Febrer",
    "MARCH": "Març",
    "APRIL": "Abril",
    "MAY": "Maig",
    "JUNE": "Juny",
    "JULY": "Juliol",
    "AUGUST": "Agost",
    "SEPTEMBER": "Setembre",
    "OCTOBER": "Octubre",
    "NOVEMBER": "Novembre",
    "DECEMBER": "Desembre"
   }

For use in the template we use the TranslaterPipe as follows

   <ion-label>{{ 'TAXES' | translate }}</ion-label>

For change the current language and translate values in the application we use TranslateService. First import it and set the default language, next change the language to the user language.


   
   import { Component } from '@angular/core';

   import { NavController} from 'ionic-angular';
   import { TranslateService } from 'ng2-translate';

   @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
   })

   export class HomePage {
      items: string[];

      userLang: string = navigator.language.split('-')[0];

      constructor(public navCtrl: NavController, 
                  public translate: TranslateService) {

         this.translate.setDefaultLang('en');
         this.translate.use(this.userLang);

         this.translate.get(["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY",
                            "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER",
                            "NOVEMBER", "DECEMBER"])
                       .subscribe(months => {
                    
                          this.items = [months.JANUARY, months.FEBRUARY, 
                                        months.MARCH, months.APRIL, 
                                        months.MAY, months.JUNE, 
                                        months.JULY, months.AUGUST,
                                        months.SEPTEMBER, months.OCTOBER,
                                        months.NOVEMBER, months.DECEMBER];
                       });     

      }
   }

The TranslateService provides a get, it take the string that need translate form the assets, subscribe to the observable and return the translate string.

And now we can use in the template, in this case loading the months in a button using a ngFor loop
  

   <ion-list inset>
      <button ion-item *ngFor="let item of items" 
                          (click)="itemSelected(item)">
         {{ item }}
      <button>
   </ion-list>

And the result looks like this


2 comentaris:

  1. Hi there! Another way to localize your app is to use an online l10n tool and my suggestion would be to have a look at https://poeditor.com

    ResponElimina
    Respostes
    1. Yes, I also looked at it, probably it is more professional but I was looking some easy and I found it a good choice

      Elimina