From 5c2fa6acf52f4c5ec8c3850ec11155a2de38f9aa Mon Sep 17 00:00:00 2001 From: Matthew Griffin Date: Fri, 2 Aug 2024 09:56:32 +0100 Subject: [PATCH] Add external link directive to easily set required attributes --- .../external-link.directive.spec.ts | 19 +++++++++++++++++++ src/app/directives/external-link.directive.ts | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/app/directives/external-link.directive.spec.ts create mode 100644 src/app/directives/external-link.directive.ts diff --git a/src/app/directives/external-link.directive.spec.ts b/src/app/directives/external-link.directive.spec.ts new file mode 100644 index 0000000..7e0ca51 --- /dev/null +++ b/src/app/directives/external-link.directive.spec.ts @@ -0,0 +1,19 @@ +import { ElementRef } from '@angular/core'; +import { ExternalLinkDirective } from './external-link.directive'; + +describe('ExternalLinkDirective', () => { + let element: ElementRef; + + beforeEach(() => { + element = { + nativeElement: jasmine.createSpyObj('nativeElement', ['setAttribute']), + }; + }); + + it('should set required attributes on element', () => { + const directive = new ExternalLinkDirective(element); + expect(directive).toBeTruthy(); + expect(element.nativeElement.setAttribute).toHaveBeenCalledWith('target', '_blank'); + expect(element.nativeElement.setAttribute).toHaveBeenCalledWith('rel', 'noreferrer'); + }); +}); diff --git a/src/app/directives/external-link.directive.ts b/src/app/directives/external-link.directive.ts new file mode 100644 index 0000000..f08d956 --- /dev/null +++ b/src/app/directives/external-link.directive.ts @@ -0,0 +1,12 @@ +import { Directive, ElementRef } from '@angular/core'; + +@Directive({ + selector: '[tce-external-link]', + standalone: true, +}) +export class ExternalLinkDirective { + constructor(private element: ElementRef) { + this.element.nativeElement.setAttribute('target', '_blank'); + this.element.nativeElement.setAttribute('rel', 'noreferrer'); + } +}