Lee Gunn
Lee Gunn

Reputation: 8656

Simple anchor tag with href causing page refresh in Angular

I have a web component that uses a simple anchor tag with an href pointing to a route.

When the link is clicked, the application reloads.

I can't use routerLink (the web component isn't Angular). What is the best way to avoid the page reload?

Upvotes: 0

Views: 1235

Answers (1)

Lee Gunn
Lee Gunn

Reputation: 8656

To get around this problem, I listen for clicks on "a" tags and prevent the default behaviour if it doesn't contain a "routerlink" attribute.

  @HostListener('window:click', ['$event'])
  onClick(e: any) {
    const path = e.composedPath() as Array<any>;

    const firstAnchor = path.find(p => p.tagName && p.tagName.toLowerCase() === 'a');
    if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
      const href = firstAnchor.getAttribute('href');

      this.router.navigateByUrl(href);

      e.preventDefault();
    }
  }

Upvotes: 3

Related Questions