diff --git a/README.md b/README.md index ee2a27b5..f50fe03b 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,7 @@ In the html page: - `reloadLang(lang: string): Observable`: Calls resetLang and retrieves the translations object for the current loader - `resetLang(lang: string)`: Removes the current translations for this lang. /!\ You will have to call `use`, `reloadLang` or `getTranslation` again to be able to get translations - `getBrowserLang(): string | undefined`: Returns the current browser lang if available, or undefined otherwise +- `getBrowserCultureLang(): string | undefined`: Returns the current browser culture language name (e.g. "de-DE" if available, or undefined otherwise #### Write & use your own loader If you want to write your own loader, you need to create a class that implements `TranslateLoader`. diff --git a/src/translate.service.ts b/src/translate.service.ts index 575a3218..a9adc4ed 100644 --- a/src/translate.service.ts +++ b/src/translate.service.ts @@ -361,6 +361,11 @@ export class TranslateService { this.translations[lang] = undefined; } + /** + * Returns the language code name from the browser, e.g. "de" + * + * @returns string + */ public getBrowserLang(): string { if(typeof window === 'undefined' || typeof window.navigator === 'undefined') { return undefined; @@ -379,4 +384,20 @@ export class TranslateService { return browserLang; } + + /** + * Returns the culture language code name from the browser, e.g. "de-DE" + * + * @returns string + */ + public getBrowserCultureLang(): string { + if (typeof window === 'undefined' || typeof window.navigator === 'undefined') { + return undefined; + } + + let browserCultureLang: any = window.navigator.languages ? window.navigator.languages[0] : null; + browserCultureLang = browserCultureLang || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage; + + return browserCultureLang; + } } diff --git a/tests/translate.service.spec.ts b/tests/translate.service.spec.ts index 20f4ad4d..a85b74f4 100644 --- a/tests/translate.service.spec.ts +++ b/tests/translate.service.spec.ts @@ -294,6 +294,12 @@ describe('TranslateService', () => { expect(browserLang).toBeDefined(); expect(typeof browserLang === 'string').toBeTruthy(); }); + + it('should be able to get the browserCultureLang', () => { + let browserCultureLand = translate.getBrowserCultureLang(); + expect(browserCultureLand).toBeDefined(); + expect(typeof browserCultureLand === 'string').toBeTruthy(); + }); }); describe('MissingTranslationHandler', () => {