0

I'm trying to put some anchors (<a> elements) within a larger clickable element (also <a>), which is a routerLink.

A simplified layout:

<div>
  <a [routerLink]="['/details', item.id]">
    <div>Lots of visual elements...</div>
    <div><a href="https://wikipedia.org">click here for more info...</a></div>
  </a>
</div> 

Simple Plunker example

Looks like the outside [routerLink] intercepts all clicks within, so wikipedia link still navigates to details view, although it displays a wikipedia address on hover. The same happens even if the nested link is also a [routerLink].

Is there a way to suppress the outside [routerLink] when clicking on the nested link?

Daria
  • 737
  • 7
  • 13

1 Answers1

0

You can replace the parent anchor tag with a div tag, and it will work:

<div>
  <div [routerLink]="['/details', item.id]">
    <div>Lots of visual elements...</div>
    <div><a href="https://wikipedia.org">click here for more info...</a></div>
  </div>
</div> 

Updated Plunker


Updated answer:

Because you don't want to load the detail component you need to do something more here:

You want to prevent the click behaviour of the parent routerLink. So you need event.stopPropagation see answers here.

So what you need to do is this:

Create a function externalLink in your App-Component:

externalLink(event, link: string){
    event.stopPropagation();
    window.location.href = link;
}

The anchor now looks like this:

<a (click)="externalLink($event, 'https://wikipedia.org')">
    Nested external link: check wikipedia
</a>

Check out the Plunker.

Community
  • 1
  • 1
Philipp Kief
  • 8,172
  • 5
  • 33
  • 43
  • It at least ends up at wikipedia. But before it does it navigates to the outer link (displays details briefly). This can be seen in Plunker, and is even more apparent in my real-life application. Additionally, the nested [routerLink] doesn't work. – Daria Nov 29 '16 at 13:34
  • please check out my updated answer, I hope it helps you ;) – Philipp Kief Nov 29 '16 at 14:25
  • it's still not ideal. So that this link looks like a proper link you need to leave `href="https://wikipedia.org"` there. This way it can be hovered and right-clicked in a usual manner. However, `ctrl+click` does too much - it does what the `(click)` does - changes the current page to wikipedia - and also opens wikipedia link in a new tab. So you'd need to add more logic in your method, but it all becomes too cumbersome. I was wondering if there's a simpler and more elegant solution. – Daria Nov 29 '16 at 15:39