In short it is not possible to change the locale without reloading the app as the translation work is done by Angular
compiler.
As of today you have two options when using official Angular i18n
:
In this case a separate bundle will be created for every locale and you'll have to swap the whole application, i.e. reload it.
When you internationalize with the AOT compiler, you must pre-build a
separate application package for each language and serve the
appropriate package based on either server-side language detection or
url parameters.
This approach is less performant but you'll not necessarily need a bundle per language.
In this case you load your translation file with webpack
and provide it to Angular
compiler during bootstrap.
The JIT compiler compiles the app in the browser as the app loads.
Translation with the JIT compiler is a dynamic process of:
- Importing the appropriate language translation file as a string constant.
- Creating corresponding translation providers for the JIT compiler.
- Bootstrapping the app with those providers.
Although in the official documentation they only have examples with useValue
providers, I'm pretty sure you can use useFactory
to provide TRANSLATIONS
and LOCALE_ID
based on your configuration.
You'll still have to re-bootstrap your app upon language change, which, in turn, means reloading, but hey, the user have this bundle cached in the browser, so the reload should be pretty fast.
Anyways, as of now, if you want to get really dynamic translations I'd suggest you to use ngx-translate.
Besides translate
pipe and service they have this nice speculative polyfill that might save you some headache when code translations will be supported officially by Angular i18n
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…