angularlocaleangular2-pipe

Dynamically change locale for DatePipe in Angular 2


I'm making an Angular project where the user has the ability to switch languages. Is it possible to make the locale dynamic?

I have seen that you can add it in the NgModule, but I'm guessing it's not dynamic when I put it there? Or can I change it somehow through a service or something?


Solution

  • Using providers, you can change your default locale in your NgModule.

    To do this, you need to import LOCALE_ID from angular/core and fetch your locale language to pass the same to providers.

    import { LOCALE_ID } from '@angular/core';
    
    @NgModule({
        imports: [//your imports],
        providers: [
            { provide: LOCALE_ID, useValue: "en-US" }
        ]
    })
    
    ...
    ...
    {
      provide: LOCALE_ID,
      deps: [SettingsService],      // Some service handling global settings
      useFactory: (settingsService) => settingsService.getLanguage()  // Returns the locale string
    }