Wayne Kaskie
Wayne Kaskie

Reputation: 3483

How to disable url changes with Angular routing

My Angular 7 app needs to be rendered in an iFrame. Due to the peculiar nature of the system, I need to prevent the URL from changing, or maybe I should say that I need Angular not to expect the URL to change.

I've found posts that show how to prevent it on specific routing calls, but the URL is updated when the app loads too.

The objective is to maintain the URL like: website.com/applicaition, even when the route changes such that there is no update to the window.location.

https://website.com/application [desired for every view] https://website.com/application/home [NOT desired for ANY view]

Thanks, Wayne

Upvotes: 4

Views: 19176

Answers (2)

Wayne Kaskie
Wayne Kaskie

Reputation: 3483

If you don't wish to have the URL updated, at all, you need to do two things.

First, add:

{ initialNavigation: false }

to the router settings like this:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '**', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { initialNavigation: false })],
  exports: [RouterModule]
})

Unfortunately, I couldn't find a way to update this globally, so you will need to set the following for each navigation point in the app.

With router-links:

<a routerLink="/home" routerLinkActive="active" skipLocationChange="true" >Home</a>

With ts navigation calls:

router.navigate(['/home'], { skipLocationChange: true });

(Ref: https://angular.io/api/router/NavigationExtras)

I hope this helps!

Upvotes: 8

Zze
Zze

Reputation: 18805

A better approach would be to implement a route guard at the root route (or a wildcard) that just always returns false.

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: '**',
        canActivate: [NeverActivate]
      }
    ])
  ],
  providers: [NeverActivate, UserToken, Permissions]
})


@Injectable()
class NeverActivate implements CanActivate {

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return false; // never allow activation
  }
}

Upvotes: -1

Related Questions