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:
- Import the locales we want to support
- Register the locales
- 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'); } }