Created
January 27, 2022 11:34
-
-
Save ChazUK/84014217b8e33b1af50f3706197fe65e to your computer and use it in GitHub Desktop.
RouterLink with support for external links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @angular-eslint/directive-selector */ | |
import { isPlatformBrowser, LocationStrategy } from '@angular/common'; | |
import { | |
Directive, | |
HostBinding, | |
HostListener, | |
Inject, | |
Input, | |
OnChanges, | |
OnDestroy, | |
PLATFORM_ID, | |
} from '@angular/core'; | |
import { | |
ActivatedRoute, | |
Event, | |
NavigationEnd, | |
Params, | |
QueryParamsHandling, | |
Router, | |
UrlTree, | |
} from '@angular/router'; | |
import { Subject, Subscription } from 'rxjs'; | |
@Directive({ selector: 'a[myRouterLink],area[myRouterLink]' }) | |
export class MyRouterLinkWithHrefDirective implements OnChanges, OnDestroy { | |
@HostBinding('attr.target') @Input() target!: string; | |
@Input() queryParams?: Params | null; | |
@Input() fragment?: string; | |
@Input() queryParamsHandling?: QueryParamsHandling | null; | |
@Input() preserveFragment!: boolean; | |
@Input() skipLocationChange!: boolean; | |
@Input() replaceUrl!: boolean; | |
@Input() state?: { [k: string]: any }; | |
@Input() relativeTo?: ActivatedRoute | null; | |
private commands: any[] | null = null; | |
private subscription: Subscription; | |
@HostBinding('attr.href') href: string | null = null; | |
/** @internal */ | |
onChanges = new Subject<MyRouterLinkWithHrefDirective>(); | |
constructor( | |
private router: Router, | |
private route: ActivatedRoute, | |
private locationStrategy: LocationStrategy, | |
@Inject(PLATFORM_ID) private platformId: string, | |
) { | |
this.subscription = router.events.subscribe((s: Event) => { | |
if (s instanceof NavigationEnd) { | |
this.updateTargetUrlAndHref(); | |
} | |
}); | |
} | |
@Input() | |
set myRouterLink(commands: any[] | string | null | undefined) { | |
if (commands != null) { | |
this.commands = Array.isArray(commands) ? commands : [commands]; | |
} else { | |
this.commands = null; | |
} | |
} | |
ngOnChanges(): any { | |
this.updateTargetUrlAndHref(); | |
this.onChanges.next(this); | |
} | |
ngOnDestroy(): any { | |
this.subscription.unsubscribe(); | |
} | |
@HostListener('click', [ | |
'$event.button', | |
'$event.ctrlKey', | |
'$event.shiftKey', | |
'$event.altKey', | |
'$event.metaKey', | |
]) | |
onClick( | |
button: number, | |
ctrlKey: boolean, | |
shiftKey: boolean, | |
altKey: boolean, | |
metaKey: boolean, | |
): boolean { | |
if (button !== 0 || ctrlKey || shiftKey || altKey || metaKey) { | |
return true; | |
} | |
if ( | |
(typeof this.target === 'string' && this.target != '_self') || | |
this.urlTree === null | |
) { | |
return true; | |
} | |
if ( | |
isPlatformBrowser(this.platformId) && | |
this.isExternalLink() && | |
this.href | |
) { | |
window.open(this.href, this.target); | |
return false; | |
} | |
const extras = { | |
skipLocationChange: attrBoolValue(this.skipLocationChange), | |
replaceUrl: attrBoolValue(this.replaceUrl), | |
state: this.state, | |
}; | |
this.router.navigateByUrl(this.urlTree, extras); | |
return false; | |
} | |
private updateTargetUrlAndHref(): void { | |
if (this.isExternalLink()) { | |
this.href = this.commands ? this.commands.join('') : null; | |
return; | |
} | |
this.href = | |
this.urlTree !== null | |
? this.locationStrategy.prepareExternalUrl( | |
this.router.serializeUrl(this.urlTree), | |
) | |
: null; | |
} | |
private isExternalLink(): boolean { | |
if (this.commands === null || !isPlatformBrowser(this.platformId)) | |
return false; | |
try { | |
const url = new URL(this.commands.join('')); | |
console.log(url.toString().replace(url.origin, '')); | |
if (url.origin === location.origin) { | |
this.commands = [url.toString().replace(url.origin, '')]; | |
return false; | |
} | |
return true; | |
} catch { | |
return false; | |
} | |
} | |
get urlTree(): UrlTree | null { | |
if (this.commands === null) { | |
return null; | |
} | |
return this.router.createUrlTree(this.commands, { | |
relativeTo: this.relativeTo !== undefined ? this.relativeTo : this.route, | |
queryParams: this.queryParams, | |
fragment: this.fragment, | |
queryParamsHandling: this.queryParamsHandling, | |
preserveFragment: attrBoolValue(this.preserveFragment), | |
}); | |
} | |
} | |
function attrBoolValue(s: any): boolean { | |
return s === '' || !!s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment