1 import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
3 import { ToastrService } from 'ngx-toastr';
6 selector: '[cdCopy2ClipboardButton]'
8 export class Copy2ClipboardButtonDirective implements OnInit {
10 private cdCopy2ClipboardButton: string;
13 private elementRef: ElementRef,
14 private renderer: Renderer2,
15 private toastr: ToastrService
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);
25 private getInputElement() {
26 return document.getElementById(this.cdCopy2ClipboardButton) as HTMLInputElement;
29 @HostListener('click')
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);
42 this.toastr.success('Copied text to the clipboard successfully.');
44 this.toastr.error('Failed to copy text to the clipboard.');