]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core'; |
2 | ||
494da23a | 3 | import { ToastrService } from 'ngx-toastr'; |
11fdf7f2 TL |
4 | |
5 | @Directive({ | |
6 | selector: '[cdCopy2ClipboardButton]' | |
7 | }) | |
8 | export class Copy2ClipboardButtonDirective implements OnInit { | |
9 | @Input() | |
10 | private cdCopy2ClipboardButton: string; | |
11 | ||
12 | constructor( | |
13 | private elementRef: ElementRef, | |
14 | private renderer: Renderer2, | |
494da23a | 15 | private toastr: ToastrService |
11fdf7f2 TL |
16 | ) {} |
17 | ||
18 | ngOnInit() { | |
19 | const iElement = this.renderer.createElement('i'); | |
11fdf7f2 TL |
20 | this.renderer.addClass(iElement, 'fa'); |
21 | this.renderer.addClass(iElement, 'fa-clipboard'); | |
22 | this.renderer.appendChild(this.elementRef.nativeElement, iElement); | |
23 | } | |
24 | ||
25 | private getInputElement() { | |
26 | return document.getElementById(this.cdCopy2ClipboardButton) as HTMLInputElement; | |
27 | } | |
28 | ||
29 | @HostListener('click') | |
30 | onClick() { | |
31 | try { | |
32 | // Create the input to hold our text. | |
33 | const tmpInputElement = document.createElement('input'); | |
34 | tmpInputElement.value = this.getInputElement().value; | |
35 | document.body.appendChild(tmpInputElement); | |
36 | // Copy text to clipboard. | |
37 | tmpInputElement.select(); | |
38 | document.execCommand('copy'); | |
39 | // Finally remove the element. | |
40 | document.body.removeChild(tmpInputElement); | |
41 | ||
42 | this.toastr.success('Copied text to the clipboard successfully.'); | |
43 | } catch (err) { | |
44 | this.toastr.error('Failed to copy text to the clipboard.'); | |
45 | } | |
46 | } | |
47 | } |