4

In my Angular 6 solution, the urls have this structure:

/{language}/{app_section}/{object_id}/{view}?queryparams...

A language selector component is shared by all sections of the application, and is included in the template of one of the parent routes so that it appears in all the children routes.

When a user selects a new language, the component should replace only the {language} segment of the current route, leaving everything else unchanged, and navigate to the new route. It seems it should be straightforward to do, but I can't seem to find an easy way. Can anybody help?

udik
  • 171
  • 3
  • 12

1 Answers1

0

Yep it is possible. Read the current route, replace the language and navigate to that URL.

constructor(private _router: Router ) {
}

languageSelected(newLanguage) {
  const newUrl = this._router.url.replace(this.currentlanguage, newLanguage);
  this.router.navigateByUrl(newUrl);
}

I've assumed that this.currentLanguage contains the current language exactly as represented in the URL and the newLanguage passed to the method is also in the exact form required by the URL. A technique such as this will trigger a component refresh and temporary state will be lost.

Avin Kavish
  • 8,317
  • 1
  • 21
  • 36
  • 1
    Thank you Avin- of course this is an option. However it is the same as reading the url from the browser and fiddling with it, and it does't seem the right or elegant way. Can't believe that angular router doesn't provide a better way. – udik Oct 07 '18 at 08:55
  • It is not the same thing because if you read the URL from the browser you will get the entire URL and not the sub URL that applies to Angular router navigation and if you set the browser URL it causes a full page refresh instead of an in-Angular route change. There is also the option of using regular expressions to check the URL but this is simple and does exactly what you want, unless this is not what you want. https://en.wikipedia.org/wiki/KISS_principle – Avin Kavish Oct 07 '18 at 09:06