1 import { Component, HostListener, Input } from '@angular/core';
3 import { detect } from 'detect-browser';
4 import { ToastrService } from 'ngx-toastr';
6 import { Icons } from '~/app/shared/enum/icons.enum';
9 selector: 'cd-copy-2-clipboard-button',
10 templateUrl: './copy2clipboard-button.component.html',
11 styleUrls: ['./copy2clipboard-button.component.scss']
13 export class Copy2ClipboardButtonComponent {
14 // The text to be copied
16 private source: string;
18 // Optional: Extracts text to be copied by "id" attribute
26 // Optional: Adds text to the left of copy icon
32 constructor(private toastr: ToastrService) {}
34 private getText(): string {
35 const element = document.getElementById(this.source) as HTMLInputElement;
36 return element?.value || element?.textContent;
39 @HostListener('click')
42 const browser = detect();
43 const text = this.byId ? this.getText() : this.source;
44 const toastrFn = () => {
45 this.toastr.success('Copied text to the clipboard successfully.');
47 if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) {
48 // Various browsers do not support the `Permissions API`.
49 // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility
50 navigator.clipboard.writeText(text).then(() => toastrFn());
52 // Checking if we have the clipboard-write permission
54 .query({ name: 'clipboard-write' as PermissionName })
55 .then((result: any) => {
56 if (result.state === 'granted' || result.state === 'prompt') {
57 navigator.clipboard.writeText(text).then(() => toastrFn());
62 this.toastr.error('Failed to copy text to the clipboard.');