angular/adev/shared-docs/directives/external-link/external-link.directive.ts
Matthieu Riegler 66abff6db8 docs(docs-infra): don't use URL to check for external links (#58955)
For perf reasons, it is more efficient to not rely on creating an `URL` object. Instead we check for the explicit protocol to detect external links.

This will also force us to use relative links, so archived versions & next versions navigate on the current version of the site.

fixes #58954

PR Close #58955
2024-11-28 16:43:28 +01:00

43 lines
1.2 KiB
TypeScript

/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isPlatformBrowser} from '@angular/common';
import {Directive, ElementRef, OnInit, PLATFORM_ID, inject} from '@angular/core';
import {isExternalLink} from '../../utils/index';
import {WINDOW} from '../../providers/index';
/**
* The directive will set target of anchor elements to '_blank' for the external links.
* We can opt-out this behavior by adding `noBlankForExternalLink` attribute to anchor element.
*/
@Directive({
selector: 'a[href]:not([noBlankForExternalLink])',
host: {
'[attr.target]': 'target',
},
})
export class ExternalLink implements OnInit {
private readonly anchor: ElementRef<HTMLAnchorElement> = inject(ElementRef);
private readonly platformId = inject(PLATFORM_ID);
target?: '_blank' | '_self' | '_parent' | '_top' | '';
ngOnInit(): void {
this.setAnchorTarget();
}
private setAnchorTarget(): void {
if (!isPlatformBrowser(this.platformId)) {
return;
}
if (isExternalLink(this.anchor.nativeElement.href)) {
this.target = '_blank';
}
}
}