最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent navigation on anchor that has routerLink - Stack Overflow

programmeradmin3浏览0评论

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();
});

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();
});
Share Improve this question edited Jan 4, 2018 at 17:05 Aleksey Solovey 4,1913 gold badges17 silver badges34 bronze badges asked Jan 4, 2018 at 16:45 bobbyrne01bobbyrne01 6,76322 gold badges84 silver badges168 bronze badges 7
  • Is this Angular (2/4/5) or AngularJS? – Aleksey Solovey Commented Jan 4, 2018 at 16:51
  • Why would you place a routerLink on an anchor element, if you do not want navigation? – Armen Vardanyan Commented Jan 4, 2018 at 16:52
  • oh yeah, its angular 4 .. @ArmenVardanyan preventing navigation will only happen in certain cases – bobbyrne01 Commented Jan 4, 2018 at 16:52
  • AngularJS? The [] binding syntax is clearly Angular. not AngularJS (which is referring to 1.x versions) – Armen Vardanyan Commented Jan 4, 2018 at 16:52
  • So maybe share the cases? – Armen Vardanyan Commented Jan 4, 2018 at 16:53
 |  Show 2 more ments

4 Answers 4

Reset to default 1

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',
        ponent: HomeViewComponent,
        canDeactivate: [DeactivateGuard]
      },
      ...
    ])
  ],
  exports: [
    RouterModule,
  ],
  ... 
})

In home/deactivate-guard:

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

export class DeactivateGuard implements CanDeactivate<HomeViewComponent> {

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

In home.ponent:

export class HomeViewComponent {

  allowNavigation = true;

  canDeactivate() {
    return this.allowNavigation;
  }
}

If you really cannot remove the [routerLink] and replace it with a (click) listener to handle the logic in a class method, maybe give this a try. In your ponent class:

shouldNavigate: boolean = false; // indicated whether it is possible to navigate
constructor(public route: ActivatedRoute) {} 

And inside the HTML template:

<a [routerLink]="shouldNavigate ? (onLink | async).linkURL : route.url">My link</a>

In Angular, if anchor points to the same url the user is now on, the navigation will not occur, so depending on the circumstances, change the url to the current page's url and be done with it.

Other options: you can write a directive that handles navigation or so. Let me know if this answer is not satisfying enough, so I may pick up another approach. This one is by far the laziest.

You can use this navigation logic on the ponent. You can add (click)=" method()" method on the anchor tag and add logic on the ponent method. I faced this issue and added logic on the ponent and used return in case I want to stop navigation.

I used router in ponent. this.router.navigate([]);

In your ments under the original question you ask us to "... assume there is a toggle in the UI that disables [the navigation]".

A method I've found is to disable pointer events using css. You get to keep your routerLink and routerLinkActive css class logic, but your users won't see the navigation link down in the browser status bar, and they won't be able to click the link to navigate.

<div>
  <a id="myLink"
     [routerLink]="(onLink | async).linkURL"
     [routerLinkActive]="active"
     [style.pointer-events]="toggledOn ? 'auto' : 'none'">
    My link
  </a>
</div>
发布评论

评论列表(0)

  1. 暂无评论