Skip to content
Advertisement

Prevent navigation on anchor that has routerLink

In my markup, there is [routerLink]="(onLink | async).linkURL"

And when its there, I’m unable to stop the navigation from happening when user clicks it.

If I remove [routerLink]="(onLink | async).linkURL", the navigation is stopped as expected.

Is there a way I can stop the navigation here? I’m unable to remove [routerLink]="(onLink | async).linkURL" from the markup.

My js below is not run in the angular context btw, its plain js.

Html ..

<div>
    <a id="myLink" [routerLink]="(onLink | async).linkURL">My link</a>
</div>

Javascript ..

document.getElementById('myLink').addEventListener('click', function(event) {
  console.log('click');
  event.preventDefault();
  event.stopPropagation();
});

Answer

Angular’s standard way to enable/disable navigation from a given route is to implement a CanDeactivate route guard. Similarly, you can implement a CanActivate route guard to enable/disable navigation to a given route.

An example of a CanDeactivate route guard is shown in this stackblitz, where the state of a check box allows or prevents navigation from the “Home” page.

In app.module:

import { AppRoutingModule } from './app.routing.module';
import { DeactivateGuard } from './views/home/deactivate-guard';

@NgModule({
  imports: [ 
    AppRoutingModule, 
    ... 
  ],
  providers: [
    DeactivateGuard
  ],
  ...
})

In app.routing.module:

import { RouterModule } from '@angular/router';
import { DeactivateGuard } from './views/home/deactivate-guard';

@NgModule({
  imports: [
    RouterModule.forRoot([
      ...
      {
        path: 'home',
        component: HomeViewComponent,
        canDeactivate: [DeactivateGuard]
      },
      ...
    ])
  ],
  exports: [
    RouterModule,
  ],
  ... 
})

In home/deactivate-guard:

import { CanDeactivate } from '@angular/router';
import { HomeViewComponent } from './home.component';

export class DeactivateGuard implements CanDeactivate<HomeViewComponent> {

  canDeactivate(component: HomeViewComponent) {
    return component.canDeactivate();
  }
}

In home.component:

export class HomeViewComponent {

  allowNavigation = true;

  canDeactivate() {
    return this.allowNavigation;
  }
}
Advertisement