How to Update URL in Angular without page refresh?

In Angular, you can update the URL without a page refresh using the router.navigate() method from the @angular/router module. Here is an example of how to use it:

Step 1 – Import the Router module in your component:

import { Router } from '@angular/router';

Step 2 – Inject the Router service in the constructor:

constructor(private router: Router) { }

 

Step 3 – Use the router.navigate() method to navigate to a new URL. For example, if you want to navigate to the users URL with an id parameter, you can do it like this:

ngOnInit() {
  this.router.navigate(['users', 42]);
}

This will update the URL to http://example.com/users/42 without a page refresh.

 

You can also use router.navigate() method with optional second parameter an object that contain the option to pass along while navigating, such as queryParams, fragment and so on.

this.router.navigate(['users'], { queryParams: { id: 42 }, fragment: 'top' });

This will update the url with query params and fragment as well.

 

It’s also important to mention that when you want to navigate to the same component but with different parameters, you can use router.navigate() method with relativeTo property to avoid recreation of the component and just update the parameters.

this.router.navigate(['users', 42], { relativeTo: this.route });

This way the component will not be recreated, but instead it will receive the new parameters via the ActivatedRoute.

Leave a Comment

Your email address will not be published. Required fields are marked *