Skip to content

Instantly share code, notes, and snippets.

@StephenFluin
Last active September 29, 2023 00:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenFluin/9785d82d5d110c7a9fe3cf36af0b9b99 to your computer and use it in GitHub Desktop.
Save StephenFluin/9785d82d5d110c7a9fe3cf36af0b9b99 to your computer and use it in GitHub Desktop.
A directive to automatically make all external `a` links noopener, noreferrer, and target _blank.
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: 'a',
standalone: true,
})
export class ADirective {
constructor(public ref: ElementRef) {}
ngAfterViewInit() {
const link = this.ref.nativeElement;
if (link.hostname === window.location.hostname) {
return;
}
link.relList.add('noopener');
link.relList.add('noreferrer');
link.target = '_blank';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment