6

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.

Tom Miller
  • 431
  • 1
  • 5
  • 16

10 Answers10

6

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
}
Derrick Awuah
  • 373
  • 2
  • 5
5

This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.

I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.

So, my work around is:

  @HostListener('window:click', ['$event'])
  onClick(e: any) {
    const path = e.composedPath() as Array<any>;
    const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
    if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
      const href = firstAnchor.getAttribute('href');

      this.router.navigateByUrl(href);

      e.preventDefault();
    }
  }

Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.

Lee Gunn
  • 8,417
  • 4
  • 38
  • 33
  • Hello Lee, i'm facing the exact same issue. I'm using a external library (jointjs), and when i click inside svg element (href), my app is full reloading. I'll try to implement your work-around. But where did you put it ? – Kubadev May 28 '20 at 10:13
  • @Kubadev - Hi, you can put it on a parent component - one that is above all the children you want to watch. In my case I put it on the main root component. – Lee Gunn May 28 '20 at 10:43
  • Ok thanks! So this is intercepting the xLinkHref of joint.js and convert it for the angular router object ? Because actually, this workaround still reload my app and i directly get to the homepage.. – Kubadev May 28 '20 at 16:40
  • @Kubadev - stick a breakpoint in the code and debug it. Sounds like you might have to tweak it slightly to fit your scenario. Maybe you have to change `firstAnchor.hasAttribute('routerlink')` by changing routerlink to something else. – Lee Gunn May 29 '20 at 08:17
  • @LeeGuun it's `href = firstAnchor.getAttribute('xlink:href')` to get the nodeValue of a jointjs rectangular node. – Kubadev Aug 20 '21 at 15:08
2

change your a tag code as below

<a href="javascript:void(0);" (click)="yourClickEvent();">A Tag</a>

this will invoke yourClickEvent(); without page reload

check the stackblitz here stackblitz

Midhun P
  • 126
  • 1
  • 11
1

If you don't want to reload the page use $event.preventDefault()

<a href="#" (click)="$event.preventDefault()">
Sivaramakrishnan
  • 689
  • 1
  • 4
  • 11
1

Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.

You could also simply paste this into the console to trigger a break, and then click any of the offending elements:

['unload', 'beforeunload'].forEach(function (evName) {
    window.addEventListener(evName, function () {
        debugger; // Chance to check everything right before the redirect occurs
    });
});

source: Break when window.location changes?

pangeam
  • 21
  • 3
0

As you are using angular routes, try to use this notation: <a [routerLink]="['./']" fragment="Test">

As explain by this comment: https://stackoverflow.com/a/38159597/4916355

Giovan Cruz
  • 681
  • 9
  • 21
0

use href="javascript:void(0);"

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

Ankur Jain
  • 221
  • 1
  • 6
0

Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.

ex:

// downloading the file based on file name

<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
F. Müller
  • 3,969
  • 8
  • 38
  • 49
Shareef
  • 1
  • 1
0

In my case, the root cause was a <base> element. Apparently, links starting with # are also rewritten to be relative to the base URL, so clicking one will trigger page navigation.

ThatsJustCheesy
  • 1,370
  • 14
  • 24
-2

Since you have mentioned the web app is asp.net webforms, can you please let us know

  1. Whether the link is asp.net hyperlink control. If so, AutoEventWireUp could cause the link to be automatically submitted: Please have a look at this link

  2. If you do have asp.net server controls on the page, then you could disable by setting

    @Page AutoEventWireup="false"

    1. For the entire project, this can be disabled by setting in web.config: