hugonne
hugonne

Reputation: 431

Angular localization: just switch language, no translation needed

I've been looking at how Angular (not AngularJS) approaches localization, and it seems like it's all centered around having a translation service that will give you the translated text. It seems like a lot more than I actually need. I'm writing a web site that will serve dashboards both in English and Spanish, and all I need is for a service that shows text that we already translated in one language or the other depending on what the user selects. Would I need to still use the same approach, and just skip the translation service part, or doy you guys know of another library that will just take care of switching languages?

I'm new to Angular (I come from a .NET world - where localization is managed a little differently), so any help is appreciated.

Thanks.

Upvotes: 3

Views: 2694

Answers (1)

Benedikt Schmidt
Benedikt Schmidt

Reputation: 2278

You can take a look at ngx-translate.

It's based on classic raw key-value pairs that can be served thorugh translation files or other self implemented loading methods like http calls to a file (if you don't want to serve the translation files with your app). The service usually is initiated with a default language and a fallback language. You can switch languages programmatically, the service will then try to load another input file (or whatever you've implemented to get the translations for a language). Here's an example for initiation and switching the language.

constructor(private translate: TranslateService) {
    // 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('en');
}

switchLanguage(language:string) {
    // switch to another language
    this.translate.use(language);
}

The translation values can be bound to the frontend in multiple ways, some work so that you don't even have to reload anything when changing the language, it will switch all values automatically, but they are limited in use. Other ways may nee a reload of the components that are currently shown.

Here's an example that works without reloading.

<!-- translation value with the key "hello" in the currently set language -->
<div translate>hello</div>

For more information, check their page, it's pretty well documented.

Upvotes: 3

Related Questions