Tom Miller
Tom Miller

Reputation: 451

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.

Upvotes: 8

Views: 26268

Answers (10)

ThatsJustCheesy
ThatsJustCheesy

Reputation: 1491

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.

Upvotes: 1

Shareef
Shareef

Reputation: 1

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>

Upvotes: 0

Lee Gunn
Lee Gunn

Reputation: 8656

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.

Upvotes: 5

Derrick Awuah
Derrick Awuah

Reputation: 399

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
}

Upvotes: 8

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:

Upvotes: -2

Ankur Jain
Ankur Jain

Reputation: 221

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.

Upvotes: 0

Midhun P
Midhun P

Reputation: 126

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

Upvotes: 2

Giovan Cruz
Giovan Cruz

Reputation: 721

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

Upvotes: 0

pangeam
pangeam

Reputation: 21

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?

Upvotes: 1

Sivaramakrishnan
Sivaramakrishnan

Reputation: 739

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

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

Upvotes: 1

Related Questions