简体   繁体   English

如何防止Angular应用中routerlink的默认点击行为?

[英]How to prevent default click behavior of a routerlink in angular app?

Even though this is not angular specific in theory it needs to be solved in ng app and none of the examples work. 尽管理论上这不是特定于角度的,但仍需要在ng app中解决,并且所有示例均无作用。 I've seen all the answers in SO but none of those solutions seem to work in real life Angular7 app. 我已经看到了所有的答案,但是这些解决方案似乎都无法在现实生活中的Angular7应用程序中工作。 For example none of the following work : 例如,以下任何一项都不起作用:

<!-- option 1 -->
<a class="nav-link" [routerLink]='["/properties", sessionId]'
 (click)="$event.stopPropagation()">Properties
</a>
<!-- option 2 -->
<a class="nav-link" [routerLink]='["/properties", sessionId]'
 (click)="$event.stopPropagation();false">Properties
</a>
<!-- option 3 -->
<a class="nav-link" [routerLink]='["/properties", sessionId]'
 (click)="$event.preventDefault()">Properties
</a>
<!-- option 4 -->
<a class="nav-link" [routerLink]='["/properties", sessionId]'
 (click)="$event.preventDefault();false">Properties
</a>

Creating a method for handler in component.ts and calling either function with or without returning false does not work either. 在component.ts中为处理程序创建方法,并调用带有或不返回false的函数均不起作用。

In addition, I don't want to disable link because it needs to be draggable / openable in other browser tab/window. 另外,我不想禁用链接,因为它需要在其他浏览器选项卡/窗口中可拖动/打开。

EDIT: Here is https://github.com/angular/angular/issues/21457 and I can make it to work by adding an element inside anchor and have the click for the inside element like this: 编辑:这是https://github.com/angular/angular/issues/21457 ,我可以通过在锚点内添加元素并使它像这样单击内部元素来使其工作:

(click)="$event.stopPropagation();$event.preventDefault()"

My real world example has mat-icon inside anchor so I use that but in link above a span inside is suggested. 我在现实世界中的示例在锚点内部有mat-icon,因此我可以使用它,但建议在跨度上方的链接中使用。

The reason routerLink does not respect preventDefault of the is described here . 的描述的routerLink理由不尊重的preventDefault 这里

The solution is to create inner element for anchor if there already isn't one (like icon). 解决方案是为锚点创建内部元素(如果没有的话)(如图标)。 In the link above a span is created inside but I have icons inside anchors which I omitted from the question for clarity: 在上面的链接中创建了一个跨度,但是在锚点中有一些图标,为清楚起见,我从问题中省略了它们:

  <a class="nav-link" [routerLink]='["/map", sessionId]'>
    <mat-icon class="tab-nav-item-icon" (click)="$event.stopPropagation();$event.preventDefault()">map</mat-icon>
  </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM