Ngx-translate: any better solution?


#1

Hi,

I’m using ngx-translate for the translation of my app. Here is the docu of it: https://ionicframework.com/docs/resources/ng2-translate/

In my opinion it is not so nice to use. In HTML it is ok but if you want to use it in TS it is much stuff. If you want to use it for example for an Alert, you have to do something like this:

translate.get(['noButton', 'yesButton']).subscribe(
    buttons => {
        let buttons = [
            {
                text: buttons.noButton,
                role: "cancel"
            },
            {
                text: buttons.yesButton,
                handler: () => {
                    // do something
                }
            }
        ];
    }
);
translate.get(['alertTitle', 'alertSubTitle']).subscribe(
    alert => {
        let alertMsg = this.alertCtrl.create({
            title: alert.alertTitle,
            subTitle: alert.alertSubTitle,
            buttons: buttons
        });
        alert.present();        
    }
);

And that for every translation… Isn’t there a better way? For example to do it with one line for the translation like this:

...
let buttons = [
    {
        text: translation.get('noButton'),
        role: "cancel"
    },
    {
        text: translation.get('yesButton'),
        handler: () => {
            // do something
        }
    }
];
...

#2
translate.instant("path.to.translation");

#3

You only have to subscribe to the translation service if you have something like a language switcher on your current page.


#4

Ok thank you guys!

And maybe another question:

Must I insert the following on every page controller where I am using translations or is it enouth to add it for example in the app.component.ts controller?

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

// The language to use. ToDo: Should be changed to the user's locale.
translate.use(constants.DEFAULT_LANG);

#5

Only in the app component :slight_smile:


#6

Ok thank you. But I have still to import the TranslateService on each page, do I?


#7

Sure you have to do that


#8

Only if you use it in the ts component, if you’re only using the pipe in your HTML it’s not necessary.


#9

I will add this kind of usage in the docs!