1 import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
2 import { I18n } from '@ngx-translate/i18n-polyfill';
4 import { ToastrService } from 'ngx-toastr';
7 selector: '[cdCopy2ClipboardButton]'
9 export class Copy2ClipboardButtonDirective implements OnInit {
11 private cdCopy2ClipboardButton: string;
13 private formatted = 'no';
16 private elementRef: ElementRef,
17 private renderer: Renderer2,
18 private toastr: ToastrService,
23 const iElement = this.renderer.createElement('i');
24 this.renderer.addClass(iElement, 'fa');
25 this.renderer.addClass(iElement, 'fa-clipboard');
26 this.renderer.setAttribute(iElement, 'title', this.i18n('Copy to clipboard'));
27 this.renderer.appendChild(this.elementRef.nativeElement, iElement);
30 private getInputElement() {
31 return document.getElementById(this.cdCopy2ClipboardButton) as HTMLInputElement;
34 @HostListener('click')
37 const tagName = this.formatted === '' ? 'textarea' : 'input';
38 // Create the input to hold our text.
39 const tmpInputElement = document.createElement(tagName);
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);
48 this.toastr.success('Copied text to the clipboard successfully.');
50 this.toastr.error('Failed to copy text to the clipboard.');