Check out our Angular Book Series.

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:


<router-outlet></router-outlet>

And add these routes to the routing module:


const routes: Routes = [
{
path: 'new',
component: View1Component
},
{
path: 'edit',
component: View1Component
}
];

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:


<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:


import { 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:


constructor(private location: Location) { }

Now, in our onSwitch, use the replaceState method:


onSwitch() {
this.location.replaceState('/edit');
}

This should work:

Play with the sample here.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.