Dynamically change locale for DatePipe in Angular 2

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 locale string
}

Hope this will help you.


To set locale from service you need to add LOCALE_ID provider with factory to app.module, like in @AmolBhor answer

{
  provide: LOCALE_ID,
  deps: [SettingsService],      //some service handling global settings
  useFactory: (settingsService) => settingsService.getLanguage()  //returns locale string
}

Unfortunately you cannot change language for DatePipe JIT. Angular compiler requires LOCALE_ID during bootstrapping.

There are some bug reports for Angular:

  • https://github.com/angular/angular/issues/15039 (closed - not resolved)
  • https://github.com/angular/angular/issues/16960 (closed with workaround in comments)

There are several workarounds for this:

Workaround #1

Re-bootstrapping angular module:

let _platformRef: NgModuleRef<Object>;
if(_platformRef) { _platformRef.destroy(); }
platformBrowserDynamic(providers)
    .bootstrapModule(AppModule, {providers})
    .then(platformRef => {
        _platformRef = platformRef;
    })

*This won't work for Hybrid Angular/AngularJS as there is no way do destroy AngularJS using UpgradeModule.

Workaround #2

To overwrite DatePipe, NumberPipe - whatever You need:

@Pipe({name: 'datepipe', pure: true})
export class MyDatePipe implements PipeTransform {
  transform(value: any, pattern?: string): string | null {
    // transform value as you like (you can use moment.js and format by locale_id from your custom service)
    return DateUtils.format(value);
  }
}

Workaround #3

To use library which already handle localization with custom Pipes for ex:

  • https://github.com/urish/angular2-moment
  • https://github.com/robisim74/angular-l10n

Workaround #4

Every pipe which use LOCALE_ID has private field locale or _locale, so You may override this field at that pipes on language change, as there is one instance of pipe.

That will work because TypeScript is just syntax sugar for JavaScript. And in JavaScript there are no private fields.

Also remember to process change detection in application by using tick() method in ApplicationRef.

@Injectable()
export class DynamicLocaleService {
  private i18nPipes: PipeTransform[];

  constructor(
    datePipe: DatePipe,
    currencyPipe: CurrencyPipe,
    decimalPipe: DecimalPipe,
    percentPipe: PercentPipe,
    private applicationRef: ApplicationRef,
  ) {
    this.i18nPipes = [
      datePipe,
      currencyPipe,
      decimalPipe,
      percentPipe,
    ]
  }

  setLocale(lang: string): void {
    this.i18nPipes.forEach(pipe => {
      if(pipe.hasOwnProperty("locale")) {
        pipe["locale"] = lang;
      } else if (pipe.hasOwnProperty("_locale")) {
        pipe["_locale"] = lang
      }
    })
    this.applicationRef.tick()
  }
}

Workaround #5

To reload application when language is changed.

window.location.reload()

Unfortunately all of above are workarounds.

But there is also another solution - you can have multiple bundles for each language, which probably will be better approach as app will be faster. But this solution is not applicable for every application and doesn't answer the question.