]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/copy2clipboard-button.directive.ts
005b20157583a936459b7925335d1cacd2af1285
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / shared / directives / copy2clipboard-button.directive.ts
1 import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
2
3 import { ToastrService } from 'ngx-toastr';
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,
15 private toastr: ToastrService
16 ) {}
17
18 ngOnInit() {
19 const iElement = this.renderer.createElement('i');
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 }