Angular: change language without reloading the page in ngx-translate

Here I propose to you an Angular tip & trick useful to change language without reloading the page when we use ngx-translate. Perhaps there is a more elegant solution to do that (if you find it, don’t hesitate to contact me). All the trick consists in going to the home page and navigating back to the previous route. In this way we force ngx-translate to reload the modules language. This code snippet works with a multiple module internationalization structure (in other words each module has it’s own en.json and it.json files for example). So that when we will change the web application language, we will not need more to tell to the browser to reload the home page by writing window.location.href='/'. Now we will call the following method (that should be defined in the language switcher component) which will make a reload of the module language without the need to download the whole website resources. The following method makes use of the Router service which we should inject in our component class constructor.

reloadLanguage(language: string) {
    this.translateService.use(language);
    this.translateService.setDefaultLang(language);
    const prev = this.router.url;
    this.router.navigate(['/']).then(data => {
      this.router.navigate([prev]);
    });
  }