Here we comes with another question.
Today the theme is Angular 2, Javascript and the navigator class.
With this code we will obtain the language from the browser:
loadLanguage() {
let idioma = navigator.language;
if(idioma === 'ca' || idioma == 'es' || idioma == 'gl' || idioma == 'va' || idioma == 'eu' || idioma == 'en' || idioma == 'fr') {
this.idioma = idioma;
} else {
this.idioma = "en";
}
}
Show the nagivator object with console.log(navigator); to see what are you interested in.
Another question related with this theme is to externalice the content of your web in Angular2.
For do that I pass you my example code:
This method loads the dictionary with all the traductions and the possible languages:
loadDictionary() { this.dictionary = { titol: {ca: 'El Temps a Espanya!', es: '¡El Tiempo en España!', en: 'The Weather in Spain!', fr: 'String1InSpanish', gl: 'O tempo en España!', va: 'El Temps a Espanya!', eu: 'Eguraldia Espainian!'}, descripcio: { ca: 'Troba les prediccions meteorològiques de tots els municipis espanyols durant els propers quatre dies.', es: 'Encuentra las prediciones meteorológicas de todos los municipios españoles durante los próximos cuatro días.', en: 'Find weather forecasts for all Spanish municipalities over the next four days.', fr: 'Trouvez les prévisions météo pour toutes les municipalités espagnoles au cours des quatre prochains jours.', gl: 'Atopar as previsións do tempo para todos os municipios españois durante os próximos catro días.', va: 'Troba les prediccions meteorològiques de tots els municipis espanyols durant els propers quatre dies.', eu: 'Aurki eguraldi Espainiako udalerri guztietako iragarpenak hurrengo lau egunetan zehar.'} }; } This method obtaions the translation of a key string in a language: getTranslation(inStringId: string, inLanguageId: string) { let labelTexts = this.dictionary[inStringId]; let translation; if (labelTexts) { translation = labelTexts[inLanguageId]; } if (translation == null) { translation = inStringId; console.error(inStringId + ' has no defined text for language ' + inLanguageId); } return translation; } And this method loads the texts you need in your web: loadTexts() { this.titol = this.getTranslation("titol", this.idioma); this.descripcio = this.getTranslation("descripcio", this.idioma); } This is my way! There are another possibilities! For any questio, don't doubt ask me! Try it and have fun! |