Created
January 23, 2018 12:39
-
-
Save porqz/e293de4c8015e358b982b077abcc2776 to your computer and use it in GitHub Desktop.
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
import { Directive, HostListener, Input, OnDestroy, OnInit } from '@angular/core'; | |
@Directive({ | |
selector: '[copyToClipboard]' | |
}) | |
export class CopyToClipboardDirective implements OnInit, OnDestroy { | |
private static copyableElement: HTMLTextAreaElement; | |
private static createCopyableElement(): void { | |
const copyableElement = document.createElement('textarea'); | |
Object.assign(copyableElement.style, { | |
bottom: '-100%', | |
opacity: 0, | |
position: 'fixed', | |
right: '-100%', | |
zIndex: -9999 | |
}); | |
document.body.appendChild(copyableElement); | |
CopyToClipboardDirective.copyableElement = copyableElement; | |
} | |
private static removeCopyableElement(): void { | |
const { copyableElement } = CopyToClipboardDirective; | |
if (copyableElement) { | |
copyableElement.remove(); | |
} | |
} | |
@Input() public textToCopy: string = ''; | |
@HostListener('click') public hostElementClicked(): void { | |
this.copyToClipboard(this.textToCopy); | |
} | |
public ngOnInit(): void { | |
const { copyableElement, createCopyableElement } = CopyToClipboardDirective; | |
if (!copyableElement) { | |
createCopyableElement(); | |
} | |
} | |
public ngOnDestroy(): void { | |
CopyToClipboardDirective.removeCopyableElement(); | |
} | |
private copyToClipboard(textToCopy: string): void { | |
const { copyableElement } = CopyToClipboardDirective; | |
copyableElement.value = textToCopy; | |
copyableElement.select(); | |
try { | |
document.execCommand('copy'); | |
} catch (e) { | |
console.error(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment