angulartypescriptionic2ng2-translate

Fallback translations culture > language > default


I'm developing an Ionic2 app (Typescript) and just adding i18n.

I'm developing in my native language (en) - and looking to support cultural variants of languages (e.g. fr vs fr-CA vs vs fr-BE...). These variants will be developed and added over time.

I've used requirejs i18n in past projects, and it is able to do language fallback/merge at 3+ levels: i.e. fr-CA-Quebec > fr-CA > fr > en

I can't work out in ng2-translate how to get anything beyond 2 levels with .use('') and .setDefaultLang('')

What I'd like to achieve is:

file: /i18n/fr-CA.json:
    {
        "dinner": "souper"
    }

file: /i18n/fr.json:
    {
        "hello": "bonjour",
        "dinner": "dîner"
    }

file: /i18n/en.json:
    {
        "title" "my title",
        "hello": "hello",
        "dinner": "dinner"
    }

Thus, for a Canadian user the I'd set .use('fr-CA') and setDefaultLang('en'), and the results should be:


Solution

  • Seems no-one has been able to answer this one for me, so I came up with a solution, which seems inelegant, but is working perfectly.

    First, I set up an onLangChange handler:

    translate.onLangChange.subscribe((event: LangChangeEvent) => {
    
      var langs = translate.getLangs();
    
      if (langs.length === 3) {
        var baseObs = translate.getTranslation(langs[1]);
        baseObs.subscribe(x => {
          //Here, I extend the cultural language with keys from the base language
          translate.setTranslation(langs[2], x, true);
        });
      }
    });
    

    Next I call lang.use on both the base and cultural language variants (if this language has a culture part)

    translate.setDefaultLang('en');
    
    let defLang = translate.getBrowserCultureLang();
    
    const langParts = defLang.split('-');
    if (langParts.length > 1 && langParts[0] !== 'en')
      translate.use(langParts[0]);
    
    translate.use(defLang);