xaisoft
xaisoft

Reputation: 3451

How to update browser url when a property changes on a component?

If I browse to http:\\localhost:4300\fr, my home page gets loaded with a french translation.

I have 2 links in my navigation (Home, Contact Us).

Home points to http:\\localhost:4300\fr\home Contact Us points to http:\\localhost:4300\fr\contact

I also have a dropdown which in which the user can select a language and it will return the translated page.

For example, when I select Spanish, the links update to:

http:\\localhost:4300\es\home and http:\\localhost:4300\es\contact, but the browser url remains http:\\localhost:4300\fr.

How can I update the browser url?

Here is the code I am using when the user picks a language from the dropdown:

  translate(langCode, language) {
    const hostName = document.location.hostname.replace('www.', '');

    this.currentTrans = language;
    this.currentTransCode = langCode;
    this._caseService.GetCaseData(caseUrl,  langCode);
  }

this.currentTransCode holds the current language code

The url is contructed like this http:\\localhost:4300\ + this.currentTransCode

Upvotes: 2

Views: 2680

Answers (2)

David
David

Reputation: 34445

You can use the location object

//component or service.ts
import {Location} from '@angular/common'

constructor(private location: Location)
{
}

changeCurrentUrl()
{
    let parts = window.location.pathname.split('/');
    parts[1] = this.currentTransCode; //replaces 'fr' with 'en'
    this.changeUrl(parts.join('/'));
}
 changeUrl(url: string)
 {
    this.location.replaceState(url);
 }

Upvotes: 5

debe
debe

Reputation: 1772

To change the url, you need to load the page with the right language. For example you can get the current pathname, and replace the language with the new one, and use the new url to reload the page.

document.location.href = "/" + this.currentTransCode + location.pathname.substring(location.pathname.indexOf("/",1)) + location.hash + location.search

UPDATE:

Sorry, I miss you use Angular. In that case, you can use $location.

$location.path(newUrl);

You can get more details from here: https://www.consolelog.io/angularjs-change-path-without-reloading/

Upvotes: 0

Related Questions