Angular i18n: Get all locales at runtime

1.1k Views Asked by At

I have an app that is localized using angular-i18n to which I want to add a language switch button. This is working, however, the available languages are hard-coded, i.e. I have to specify the languages in code that the app was translated to.

Is there a way to get a list of all available locales (or in other words: is it possible to get the names of all the folders in the dist directory at runtime?)

Thanks for any answers!

2

There are 2 best solutions below

3
On

I know this doesn't answer your question but...

I highly recommend Transoloco for Angular, instead of angular-i18n:

https://ngneat.github.io/transloco/

You can inject the TransoloService and call getAvailableLangs from their language API:

https://ngneat.github.io/transloco/docs/language-api#getavailablelangs

0
On

I think what you need is to provide a country selector for users, then locales selector.

I think you can use this lib You can see that it includes many countries & locales, even currencies. For my situation, I need to provide a way for users to specify their country and locales.

With this lib, you can make your own locale or country selector.

const clm = require('country-locale-map');

clm.getAllCountries();

clm.getCountryByAlpha2('CA'); 

/*returns 

    {
        "name":"Canada",
        "alpha2":"CA",
        "alpha3":"CAN",
        "numeric":"124",
        "locales":["en_CA","fr_CA"],
        "default_locale":"en_CA",
        "currency":"CAD",
        "languages":["en","fr"],
        "capital":"Ottawa",
        "emoji":"",
        "emojiU":"U+1F1E8 U+1F1E6",
        "fips":"CA",
        "internet":"CA",
        "continent":"Americas",
        "region":"North America"
    }

*/

Note:

The lib only can be used on the backend side.