angularrouterngx-datatable

Prevent redirection through href="#" while using Angular Router


I've been working on an Angular project which includes different libraries most importantly ngx-datatable.

Routing is working without any issues except for anchor tags where href="#" where the user is redirected to / even if not required.

All the solutions that I've found suggest removing # or the whole attribute itself but I just can't do that as it requires hacking all the libraries I'll be using.

Example is from ngx-datatable where the link is supposed to Expand/Collapse a row. Instead, it redirects user to homepage.

Is there any way I can use a Router hook or something to stop navigation if the request URL is #?


Solution

  • To achieve expected result, use javascript:void(0) for href attribute instead of # (if you are able to change individually)

    <a href="javascript:void(0);"></a>
    

    Option 2: Generic solution to update all hrefs , override href attribute as mentioned in below answer Angular 2, handle anchor links with href='#'

    @Directive({
      selector : '[href]'
    })
    export class MyLinkDirective {
      @Input() href: string;
    
      @HostListener('click', ['$event'])
      noop(event: MouseEvent) {
        if(this.href.length === 0 || this.href === '#') {
          event.preventDefault();
        }
      }
    }