Angular: How to get the current locale at runtime when using AOT
Simply inject LOCALE_ID
in your constructor, e.g.
import { LOCALE_ID, Inject } from '@angular/core';
...
constructor(
@Inject(LOCALE_ID) public locale: string
) { }
The injection token LOCALE_ID
does not provide your user's language or locale, it is static and defaults to 'en-US'
unless you provide a different value for it (docs):
providers: [{provide: LOCALE_ID, useValue: 'en-GB' }]
Here's a method that gets the user's preferred language and locale:
getUsersLocale(defaultValue: string): string {
if (typeof window === 'undefined' || typeof window.navigator === 'undefined') {
return defaultValue;
}
const wn = window.navigator as any;
let lang = wn.languages ? wn.languages[0] : defaultValue;
lang = lang || wn.language || wn.browserLanguage || wn.userLanguage;
return lang;
}