0

I am following this tutorial to translate the content of my website to a couple of languages , but I would like to do it depending on the default language which is accessing to my website, and not pressing a button.

For example, if a guy from Spain access to my website, I would like to show it in Spanish, and if not, in English.

Is it possible? Basically, like Android Framework works.

bellotas
  • 2,349
  • 8
  • 29
  • 60
  • 1
    Does this help? https://stackoverflow.com/questions/2678230/how-to-getting-browser-current-locale-preference-using-javascript? What backend do you have? – Brian Dec 19 '17 at 12:32

2 Answers2

0

You can detect language from navigator object. Navigator have languages array. First language of array is default for browser.

export class App {

  constructor(private winRef: WindowRef) {

    console.log('navigator object', winRef.nativeWindow.navigator);
  }
}
Savan S
  • 407
  • 4
  • 19
0

To access to the language of your browser it is just needed to use:

var lang = navigator.language;

Solution 1

So, one example for using in is the following:

//Used for the internationalization
  constructor(
    private translate: TranslateService,
  ) {
    //Getting the language of the browser
    var lang = navigator.language;
    this.switchLanguage(lang);
  }

  switchLanguage(language: string) {
    //console.log(language);
    if (language == "en") this.translate.use("en");
    else if (language == "es") this.translate.use("es");
    else this.translate.use("en");
  }

In this case, in the constructor of your component, you get the language of your browser and you call to switchLanguageto define which one should you use.

Solution 2 (works better for me)

Another solution would be just to create a new file, for example translation.service.ts

for managing the methods from that file:

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Injectable()
export class TranslationService {
    constructor(
        //Used for the internationalization
        private translate: TranslateService,
    ) { }

    switchLanguage(language: string) {
        console.log(language);
        if (language == "es" || language == "es-ar" || language == "es-bo" || language == "es-cl" || language == "es-co" || language == "es-cr" || language == "es-do" || language == "es-ec"
            || language == "es-sv" || language == "es-gt" || language == "es-hn" || language == "es-mx" || language == "es-ni" || language == "es-pa" || language == "es-py"
            || language == "es-pe" || language == "es-er" || language == "es-es" || language == "es-uy" || language == "es-ve") this.translate.use("es");
        else this.translate.use("es");
    }
}

And after it just injecting it to the component that you want to translate

bellotas
  • 2,349
  • 8
  • 29
  • 60