Adding I18n support on an ionic 2 app

Adding I18n support on an ionic 2 app

I found many tutorials, but none was really geared toward rc4.

So here is a short and simple way to add I18n support for an ionic 2 app.

First install the ng2-translate plugin:

npm install ng2-translate --save

Then changes to the following two filesĀ app.module.ts and app.component.ts are necessary.

In the app.module.ts add the following to your imports statement:

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

The app.component.ts needs some configuration. Add the following method and exchange the list of languages with your languages.

translateConfig() {
 var userLang = navigator.language.split('-')[0]; // use navigator lang if available
 userLang = /(de|en)/gi.test(userLang) ? userLang : 'en';

 // this language will be used as a fallback when a translation isn't found in the current language
 this.translate.setDefaultLang('en');

 // the lang to use, if the lang isn't available, it will use the current loader to get them
 this.translate.use(userLang);
}

You also need to add the translation service to the constructor:

public translate: TranslateService

and call the method in the constructor.

After that you can use the translate pipe on any page you want:

{{"path.to.translation | translate}}

And how do you store your texts? In a json file per language in the src/app/i18n folder. The english file for the above example would look like this:

en.json
{
    "path": {
        "to": {
            "translation": "test"
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.