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?
Using
providers
you can change your default locale in yourNgModule
. to do this You need to import LOCALE_ID from angular/core and fetch your locale language to pass the same to providers.Hope this will help you.
To set locale from service you need to add
LOCALE_ID
provider with factory toapp.module
, like in @AmolBhor answerUnfortunately you cannot change language for DatePipe JIT. Angular compiler requires
LOCALE_ID
during bootstrapping.There are some bug reports for Angular:
There are several workarounds for this:
Workaround #1
Re-bootstrapping angular module:
*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:
Workaround #3
To use library which already handle localization with custom Pipes for ex:
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.Workaround #5
To reload application when language is changed.
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.
Have your Service like
And in App.module.ts
first import localization that you need , say
Than under providers section
At the end
Hope it will help someone
if you want to change locale dynamically , inject LocaleService in your desired component and use registerCulture method , pass your required culture into this