Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to get the current locale at runtime when using AOT

Tags:

I am compiling my project with:

ng serve --aot --i18nFile=client/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr

How can I access the locale ID at runtime? I want to show/hide elements based on the locale.

PS. I do realise that using JIT compilation I can simply do this:

providers: [ { provide: LOCALE_ID, useValue: 'fr' } ]

But I'm looking for a AOT solution. I also would rather not infer locale based on hostname or anything like that.

like image 575
williamsandonz Avatar asked May 24 '18 15:05

williamsandonz


People also ask

How do I check my browser locale?

To get the user's locale in the browser, access the first element of the languages property on the navigator object, e.g. navigator. languages[0] . The property returns an array of strings that represent the user's preferred languages.

How would you implement localization in Angular using i18n tools?

Open the angular. json file and add the following configuration. Here we have added the configuration for the Spanish language. We have provided the path and format for the i18n file and set the locale to "es." When we execute the application, the app content will be served from the i18n file path provided.

What is locale ID in Angular?

Angular uses the Unicode locale identifier (Unicode locale ID) to find the correct locale data for internationalization of text strings. Unicode locale ID. A locale ID conforms to the Unicode Common Locale Data Repository (CLDR) core specification.


1 Answers

Simply inject LOCALE_ID in your constructor, e.g.

import { LOCALE_ID, Inject } from '@angular/core';

...

constructor(
  @Inject(LOCALE_ID) public locale: string
) { }
like image 61
williamsandonz Avatar answered Oct 08 '22 03:10

williamsandonz