To change a URL without reloading the page in Angular, you can use the replaceState()
method of the Location
object.
The replaceState()
method replaces the current URL with the specified URL without reloading the page.
To use the replaceState()
method, you have to first import the Location from the @angular/common library of Angular. Then you can inject it into the constructor of the class.
Once injected, you can call the replaceState()
method and pass the new URL as an argument to this method which will replace the existing URL with the new one.
In the following example, we have bound the changeURL() method with a button’s click event. As soon as you click on this button, it will replace the /product
URL with /product/apple
without reloading the page:
import { Location } from '@angular/common'; constructor(private location: Location) { } changeURL(){ this.location.replaceState('/product/apple'); // Replaces the current url with /product/apple // You can change it to whatever URL you want }
This is how the URL will look like before and after clicking the change URL button:

You can even change the current route to any other route you want without reloading the page. To do that you just need to pass the new route as an argument to the replaceState()
method.
This is how you can do it:
changeURL(){ this.location.replaceState('/someRoute'); // Change current route to /someRoute }