Changing locale in Angular at runtime?

2020-07-16 12:48发布

问题:

I was doing some research on changing Angular locale at runtime and found this thread: How to set locale in DatePipe in Angular 2? .
Is it still the case that there is no way to change locale at runtime? I have an application that features several pipes to format number, date and language depending on the locale, but implementing many custom pipes for each locale -- rather than having the ability to change it during runtime--seems ridiculous.
What solutions would you purpose?

回答1:

I bet you are searching for this because today you're upgrading @angular/material to beta.10 and the DatePicker now uses LOCALE_ID, isn't it? I'm looking for an alternative too and had no luck.

Angular 4 i18n approach is based on the compiler, generating different bundles for different languages, so a runtime solution seems not supported by that architecture. There's work being done in Angular 6 compiler to support runtime translation changes.

For the moment, I like ngx-translate approach, they seem to subscribe to lang changes and update the DOM nodes registered with the Directive, and I'm planning to build my own DateFormat pipe based on their TranslateDirective, but about services and components using the LOCALE_ID, I think there's no chance to change their behavior at runtime. Probably there are new exported resources for extension and customization (I did read something in the changelog), so we may need to go deep into the components we want to translate.

If you take the ngx-translate approach, let's share stuff at github to build new pipes ;)