angulartypescriptinternationalization

How can I implement language switching in my Angular application using the official Angular i18n library?


I would like to enable language switching in my Angular application by using the official Angular i18n library, as the previously popular library (ngx-translate) is now in maintenance mode and will be deprecated in the future.

Specifically, I want to achieve the following:

  1. Display two buttons/icons on the user interface—one for switching to English and another for switching to French.
  2. When a user clicks one of these buttons, the language of the entire application should change accordingly.

My goal is to integrate this functionality using the built-in Angular i18n features, rather than relying on third-party libraries like ngx-translate. Is there a recommended approach or best practices for implementing this feature? Can I implement this without having to serve the build?

I have already set up basic localization using Angular's i18n library by following the official documentation. I’ve added the i18n attributes to some of my template elements, generated the translation files, and tested the language change by rebuilding the application with different language configurations (e.g., by using ng build --localize).

However, this approach only works at build time, and I am struggling to implement a way for users to dynamically switch languages at runtime (via a button or icon) without having to reload the entire application.

I expected there to be a straightforward method in the Angular i18n library to change the language based on user interaction.


Solution

  • The basic angular i18n package will build separate apps for each language file you provide. If you want to use a language switch with this package, all it will do it route them to the subfolder where the other languages are hosted.

    For example, if your english site is at www.example.com and you want a spanish translation, angular i18n will build you a separate app that you can deploy to www.example.com/es. Then, your language picker would simply redirect the user to /es.

    If you want to change the language at runtime, you should use a third party library like ngx-translate. You could implement it yourself, but you would be re-inventing the wheel. As well, I don't believe ngx-translate is in maintenance mode, their github page does not mention it.

    If you want to build it yourself, consider creating a service to fetch json files for the languages and a pipe to convert the language keys to their translated values.