jsoninternationalizationng2-translate

ng2-translate in Ionic 2.2.3, the text doesen't change with different languages


I need some help with ng2-translate in an Ionic 2(.2.3) Application. I followed this tutorial: https://www.techdiary.io/internationalization-of-ionic2-apps/ and it worked.

I created an en.json file and a small "dictionary" as well. The words I tagged with {{"Example"|translate}} got translated to the related word.

But if I change my initTranslation() to "de" instead of en

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

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

nothing will happen. What am I'm missing? I have created a de.json with the same words like the en.json file.

And is it possible to use the marked tags ( {{"Example"|translate}}) as default language? Or do I allways need to translate the tags now?

Thanks

Edit: Clearly this one:

userLang = /(fr|en|es|in|zh)/gi.test(userLang) ? userLang : 'en';

doesn't work for me. It will only change the language if I change the default language. And it will only work if I use "en". Very confusing.

Edit2:

Yep, if I use something like

userLang = 'de'

it works. But still, is it possible to use the actual html text as default language?


Solution

  • //But still, is it possible to use the actual html text as default language?

    You mean user browser language ?

    if so, use this.

    let browserLang = translate.getBrowserLang();
            translate.use(browserLang.match(/en|es/) ? browserLang: 'en')
    

    else intially {{"Example"|translate}} Example need to appear later you need to choose the language? if so, add drop down to your html

    <ul class="dropdown-menu" role="menu">
                      <li>
                          <a (click)="changeLanguage('en')">English</a>
                      </li>
                      <li>
                          <a (click)="changeLanguage('es')">Spanish</a>
                      </li>
                  </ul>
    

    .ts file

    changeLanguage(lang) {
            this.translate.use(lang);
        }