Ngx-translate: any better solution?

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
        }
    }
];
...
translate.instant("path.to.translation");
2 Likes

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

1 Like

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);

Only in the app component :slight_smile:

2 Likes

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

Sure you have to do that

1 Like

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

2 Likes

I will add this kind of usage in the docs!