Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I've seen all the answers in SO but none of those solutions seem to work in real life Angular7 app. 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.

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:

(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.

like image 500
char m Avatar asked Jun 12 '19 10:06

char m


1 Answers

The reason routerLink does not respect preventDefault is described here.

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>
like image 95
char m Avatar answered Oct 20 '22 04:10

char m