All files / src/app/shared/directives copy2clipboard-button.directive.ts

66.67% Statements 18/27
72.73% Branches 8/11
50% Functions 2/4
64% Lines 16/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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