I want to get the android device language from the app developed using Ionic3, Cordova and Angular4.
How can I get it?
window.navigator.language
worked for me with no plugin. I didn't check to see how the results compare to the Globalization plugin, but I got results like: Android: "en-us", "es-us" and on iOS: "en-US" and "es-XL"
also see https://stackoverflow.com/a/4079798/431296 -window.navigator.userLanguage
wasn't defined on either Android or iOS, so I didn't include it
You can use cordova-plugin-globalization which also offers an ionic-native wrapper. It offers a lot of useful methods, but you are probably looking for getPreferredLanguage()
or getLocaleName()
.
Installation:
ionic cordova plugin add cordova-plugin-globalization
npm install --save @ionic-native/globalization
Example:
import { Globalization } from '@ionic-native/globalization';
constructor(private globalization: Globalization) {
this.globalization.getPreferredLanguage()
.then(res => console.log(res))
.catch(e => console.log(e));
}
Follow up to David's answer, the Globalization API is deprecated.
With the ECMA Internationalization API now supported on iOS, Android and Windows devices, this plugin is not required any more. * Migrating from this plugin to the ECMA Internationalization API is explained in this Cordova blog post.
If you're using ngx-translate,
import { TranslateService } from '@ngx-translate/core';
constructor(private translate: TranslateService) {
console.log(this.translate.getBrowserLang());
}
works fine on the devices and in the browser. It's returning "en" or "de".
For ionic 5 with capacitor:
npm install @capacitor/device
npx cap sync
in code:
import { Device } from '@capacitor/device';
console.log((await Device.getLanguageCode()).value); // en-US
Ionic 4
In Ionic we call it Globalization performs operations specific to the user's locale, language, and timezone.
Installation : Terminal
ionic cordova plugin add cordova-plugin-globalization
npm install @ionic-native/globalization
Usages: Any Component or service file.
import { Globalization } from '@ionic-native/globalization/ngx';
constructor(private global: Globalization) { }
...
this.global.getPreferredLanguage()
.then(res => console.log(res))
.catch(e => console.log(e));