How do I change the URL in an Angular Application without reloading the Route?

I'm working on an Angular app, as I often do and wanted to change the the route in the URL without reloading the application. In essence, the user has just created something, we wanted to redirect the user to the edit screen, with all the data loaded. The catch was that the edit screen and create screen were the same exact component, just with different data loaded. And we didn't need to load new data because the user just entered everything; and any database specific data like a primary key was just returned from the service. How can you do that? Use the the Location lib from the Angular library. I'm going to show you how.

The Setup

First, create a new Angular application with routing. Then create a view component--I Called mine view1.

Change the main app.component.html to contain the router outlet:

view plain print about
1<router-outlet></router-outlet>

And add these routes to the routing module:

view plain print about
1const routes: Routes = [
2 {
3 path: 'new',
4 component: View1Component
5 },
6 {
7 path: 'edit',
8 component: View1Component
9 }
10];

We're going to load up the new route, and then redirect to edit on the click of a button.

Redirect

In view1.component.html, add a button:

view plain print about
1<button (click)="onSwitch()">Change URL</button>

When this button is clicked, we'll perform the URL change without loading the new route.

Move to the view1.component.ts file. First import the Location from @angular/common:

view plain print about
1import { Location } from '@angular/common';

This is important, because for some reason IntelliJ is not importing the Location object properly, and nothing works if the import is missing, or worse lost.

Location is an Angular service, so inject it into the view1 component:

view plain print about
1constructor(private location: Location) { }

Now, in our onSwitch, use the replaceState method:

view plain print about
1onSwitch() {
2 this.location.replaceState('/edit');
3 }

This should work:

Play with the sample here.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)

Comments are not allowed for this entry.