import { Directive , HostListener , ElementRef } from '@angular/core' ; import { Router } from '@angular/router' ; @ Directive ( { selector : '[intercept-links]' } ) export class InterceptLinksDirective { @ HostListener ( 'click' , [ '$event' ] ) public onClick ( $event ) { let linkEle = $event . target ; if ( linkEle . tagName !== 'A' ) { while ( linkEle . tagName !== 'A' ) { if ( linkEle === this . elementRef . nativeElement ) { return ; } linkEle = linkEle . parentElement ; } } const url = new URL ( linkEle . href ) ; if ( linkEle . getAttribute ( 'download' ) !== null ) { return ; } if ( linkEle . target === '_blank' ) { return ; } if ( url . host !== location . host ) { return ; } this . router . navigateByUrl ( url . pathname ) ; return false ; } constructor ( private router , private elementRef ) { } }