Working example for localization (i18n) will bee very much appreciated


#1

Hi all

Very very new to ionic.
I am trying to build a ionic 2 app with localization, so the user can change language inside the app. does anyone know about a up to date working example for localization (i18n), it will bee very much appreciated?

Kind regards


#2

First: add ng2-tranlate to your app npm install ng2-translate --save
Then in app.module.ts just add this in import array :

    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]
    })

and don’t forget your imports :

import { TranslateModule, TranslateLoader,
          TranslateStaticLoader } from 'ng2-translate/ng2-translate';

Finally in constructor of app.component.ts :

import { TranslateService } from 'ng2-translate/ng2-translate';


constructor(public platform: Platform, public translate: TranslateService) {
  this.platform.ready().then(() => {
      var userLang = navigator.language.split('-')[0]; // use navigator lang if available
      userLang = /(fr|en)/gi.test(userLang) ? userLang : 'en';
      // this language will be used as a fallback when a translation isn't found in the current language
      translate.setDefaultLang('en');
      // the lang to use, if the lang isn't available, it will use the current loader to get them
      translate.use(userLang);
  });
}

#3

Thanks.

Build with errors. In my app.component.ts constructor i get:
“Cannot find name translate”


#4

You have to declare it somewhere, in your constructor parameters for example.
constructor(public platform: Platform, public translate: TranslateService) {
and if it not enough use this.translate instead of translate.


#5

Hi

I got it to work with your help and some examples from https://github.com/ocombe/ng2-translate

thank you for your patience.

Kind regards