3

I noticed that dates are not properly formatted according to the browser language in my angular application when using the date pipe. To fix this, I tried to implement the suggestion from this answer in my app.module.ts. As I am using ngx-translate in my application, I used the TranslateService to get the current language like this:

{
  provide: LOCALE_ID,
  useFactory: (translate: TranslateService) => {
    console.log("Current language", translate.currentLang);
    return translate.currentLang;
  },
  deps: [TranslateService],
},

Unfortunately, this doesn't work. translate.currentLang seems to still be set to undefined here so I cannot use it the way I wanted. I assume this is because this code gets executed before I even set the preferred language in the constructor of my app.component.ts:

  constructor(
    public translate: TranslateService,
  ) {
    translate.addLangs(["en", "de"]);

    const browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|de/) ? browserLang : "en");
  }

Is there a way to make this work so I don't need to come up with some sort of workaround to get the current language in my app.module.ts?

Chris
  • 1,417
  • 4
  • 21
  • 53
  • 1
    You can probably get away with using `translate.getBrowserLang()` just like you do in your AppComponent's constructor. – Octavian Mărculescu Mar 25 '22 at 14:24
  • @OctavianMărculescu Thanks! That does indeed seem to work just fine. Would you say it is bad practice if I just move my code to set the language from the `app.component.ts` directly into the `useFactory` in the `app.module.ts`, or is that okay? That way, I would at least not have any redundant code. – Chris Mar 25 '22 at 14:31
  • 1
    I don't think it's bad, you could have it there in your app initializer just fine. – Octavian Mărculescu Mar 25 '22 at 14:41

0 Answers0