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