Rohit
Rohit

Reputation: 3136

Prevent route navigation under certain circumstances

In vanilla JS, it's easy enough to stop a link from navigating, via preventDefault(). However, in Angular, it doesn't seem to be that easy and I'm not sure what the right solution is. For example, I have a top menu in which some items are dropdowns in some conditions and should open on click, and in others should behave as normal links. I did what I thought I would normally do:

toggleMenu(event: Event) {
    event.preventDefault();
    // Usual logic goes here
}

But this doesn't stop navigation, and I'm not sure how to stop it. I can make it much more complex by creating guards on every link with a service to stop it, but that definitely feels overkill. Any advice?

Upvotes: 1

Views: 1040

Answers (1)

Reactgular
Reactgular

Reputation: 54741

It's a good question, and there isn't a clear intention in the RouterLink source code that shows there is support for disabling the click handler.

If you assign null to the router link it will route to the current route. Which is basically the same as not changing the route, but I don't know if this still triggers a route change or not.

<a [routeLink]="condition ? '/my/route/address' : null">Link</a>

condition can be a template variable or you could call a component method if you need to calculate something more complex. The key is to yield null when you want to disable the link.

Upvotes: 3

Related Questions