ngx-rocket / generator-ngx-rocket

:rocket: Extensible Angular 14+ enterprise-grade project generator
https://ngx-rocket.github.io/
MIT License
1.53k stars 216 forks source link

Proposal for setting LOCALE_ID in the app.module #547

Open ThomasBoersma opened 4 years ago

ThomasBoersma commented 4 years ago

I'm submitting a...

Current behavior

The angular pipes (like | date) in combination with the translations don't work as expected. When the current language is fr-FR you would expect a day name in French. But when I reload the app the name of the day is still in English.

Expected behavior

The name of the day should be in French.

Minimal reproduction of the problem with instructions

I used the out-of-the-box example of the generator-ngx-rocket repo.

My proposal

When you register the Angular common locales (Fr, En, De etc) and initialise the i18nService in the app.module file (for the latter instead of app.compoment file). You can set the LOCALE_ID with a factory like approach.

In app.module.ts

registerLocaleData(localeFr, 'fr-FR');
registerLocaleData(localeEn, 'en-US');
registerLocaleData(localeDe, 'de-DE');

...

  providers: [{
    provide: LOCALE_ID,
    useFactory: (i18nService: I18nService) => {
      i18nService.init(environment.defaultLanguage, environment.supportedLanguages);
      return i18nService.language;
    },
    deps: [I18nService]
  }],

Is this a better approach? I am really interested how you do it with dynamic/language dependent pipes.

sinedied commented 4 years ago

This was already discussed in a previous issue on the startkit repo: https://github.com/ngx-rocket/starter-kit/issues/16

Basically, LOCALE_ID can only be set once during app startup and do not support dynamic language changes, as it's meant for static language setup, there's nothing we can really do about it.

If you want to use the built-in pipes the best solution is to make simple wrappers like this one:

@Pipe({name: 'dynamicDate', pure: true})
export class DynamicDatePipe implements PipeTransform {
  constructor(private datePipe: DatePipe, private i18n: I18nService) {}

  transform(value: any): string|null {
    return this.datePipe.transform(value, undefined, undefined, this.i18n.language);
  }
}