diff --git a/lib/core/src/lib/clipboard/clipboard.directive.spec.ts b/lib/core/src/lib/clipboard/clipboard.directive.spec.ts index 17f84ee1a3..b568a0c286 100644 --- a/lib/core/src/lib/clipboard/clipboard.directive.spec.ts +++ b/lib/core/src/lib/clipboard/clipboard.directive.spec.ts @@ -64,6 +64,15 @@ describe('ClipboardDirective', () => { expect(clipboardService.copyToClipboard).toHaveBeenCalled(); }); + + it('should notify copy target value on keydown event', () => { + spyOn(clipboardService, 'copyToClipboard'); + fixture.nativeElement.querySelector('input').value = 'some value'; + fixture.nativeElement.querySelector('button').dispatchEvent(new KeyboardEvent('keydown', {code: 'Enter', key: 'Enter'})); + + expect(clipboardService.copyToClipboard).toHaveBeenCalled(); + }); + }); describe('CopyClipboardDirective', () => { @@ -128,6 +137,16 @@ describe('CopyClipboardDirective', () => { expect(navigator.clipboard.writeText).toHaveBeenCalledWith('text to copy'); })); + it('should copy the content of element on keydown event', fakeAsync(() => { + const spanHTMLElement = element.querySelector('span'); + fixture.detectChanges(); + spyOn(navigator.clipboard, 'writeText'); + spanHTMLElement.dispatchEvent(new KeyboardEvent('keydown', {code: 'Enter', key: 'Enter'})); + tick(); + fixture.detectChanges(); + expect(navigator.clipboard.writeText).toHaveBeenCalledWith('text to copy'); + })); + it('should not copy the content of element when click it', fakeAsync(() => { const spanHTMLElement = element.querySelector('span'); fixture.detectChanges(); diff --git a/lib/core/src/lib/clipboard/clipboard.directive.ts b/lib/core/src/lib/clipboard/clipboard.directive.ts index ee898cfb4b..48ee7cc318 100644 --- a/lib/core/src/lib/clipboard/clipboard.directive.ts +++ b/lib/core/src/lib/clipboard/clipboard.directive.ts @@ -40,13 +40,6 @@ export class ClipboardDirective { public viewContainerRef: ViewContainerRef, private resolver: ComponentFactoryResolver) {} - @HostListener('click', ['$event']) - handleClickEvent(event: MouseEvent) { - event.preventDefault(); - event.stopPropagation(); - this.copyToClipboard(); - } - @HostListener('mouseenter') showTooltip() { if (this.placeholder) { @@ -61,7 +54,12 @@ export class ClipboardDirective { this.viewContainerRef.remove(); } - private copyToClipboard() { + @HostListener('click', ['$event']) + @HostListener('keydown.enter', ['$event']) + copyToClipboard(event: MouseEvent | KeyboardEvent) { + event.preventDefault(); + event.stopPropagation(); + const isValidTarget = this.clipboardService.isTargetValid(this.target); if (isValidTarget) {