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

64.29% Statements 18/28
75% Branches 9/12
60% Functions 3/5
61.54% Lines 16/26

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 4998x   98x         98x   98x     14x 14x 14x     98x 13x 13x 13x 13x 13x     98x         196x                                 98x  
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
 
import { ToastrService } from 'ngx-toastr';
 
@Directive({
  selector: '[cdCopy2ClipboardButton]'
})
export class Copy2ClipboardButtonDirective implements OnInit {
  @Input()
  private cdCopy2ClipboardButton: string;
 
  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private toastr: ToastrService
  ) {}
 
  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.');
    }
  }
}