Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page reloads when clicking anchor element

I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.

I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".

I'm not sure what's causing the whole page to reload.

Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.

I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.

like image 324
Tom Miller Avatar asked Dec 17 '22 18:12

Tom Miller


1 Answers

It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like

<a href="#" (click)="$event.preventDefault()">

Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:

Html

<a href="#" (click)="someFunc($event)">

and in your ts:

someFunc(event) {
    event.preventDefault();
    // rest of your code here
}
like image 142
Derrick Awuah Avatar answered Dec 20 '22 06:12

Derrick Awuah