Angular configure user browser locale

Problem

Using the angular date pipe etc. we often see that by default the format is en-US instead of the expected browser language of the user.

Solution

What we have to do is quite simple:

  1. Import the locales we want to support
  2. Register the locales
  3. Configure LOCALE_ID provider using the browser language
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

// 1. Import the locales we want to support, here we import just two
import localeDe from '@angular/common/locales/de';
import localeEn from '@angular/common/locales/en';
import { LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';

// other imports ...

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
	// other imports ...
  ],
  providers: [
    // 3. Configure LOCALE_ID provider using the browser language
    {provide: LOCALE_ID, useValue: navigator.language ?? 'en' }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
    // 2. Register the locales
    registerLocaleData(localeDe, 'de');
    registerLocaleData(localeEn, 'en');
  }
 }

Paul Sterl has written 35 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>