import { Directive , ElementRef , HostListener , OnDestroy , OnInit , } from '@angular/core' ; import { ActivatedRoute , Router } from '@angular/router' ; import { Subject } from 'rxjs' ; import { map , takeUntil } from 'rxjs/operators' ; import { RouterEvent } from './router-event.type' ; Component @ Directive ( { selector : '[aerRouting]' , } ) export class RoutingDirective implements OnInit , OnDestroy { private destroyed$ = new Subject < void > ( ) ; constructor ( private element , private router , private route ) { } ngOnInit ( ) { this . route . url . pipe ( map ( ( ) => this . router . url ) , takeUntil ( this . destroyed$ ) ) . subscribe ( ( url ) => ( this . element . nativeElement . route = url ) ) ; } ngOnDestroy ( ) { this . destroyed$ . next ( ) ; } @ HostListener ( 'routeChange' , [ '$event' ] ) handleRouteChange ( event ) { this . navigateToUrl ( event ?. detail ) ; } navigateToUrl ( event ) { if ( event ?. url && event . url . startsWith ( '/' ) ) { this . router . navigateByUrl ( event . url , { replaceUrl : event . replaceUrl || false , } ) ; } else { console . warn ( `The aerRouting directive received an invalid router event.` , event ) ; } } }