Solution 1: Copy any text
HTML
<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
.ts file
copyMessage(val: string){ const selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = val; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); }
Solution 2: Copy from a TextBox
HTML
<input type="text" value="User input Text to copy" #userinput> <button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>
.ts file
/* To copy Text from Textbox */ copyInputMessage(inputElement){ inputElement.select(); document.execCommand('copy'); inputElement.setSelectionRange(0, 0); }
Solution 3: Import a 3rd party directive ngx-clipboard
<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>
Solution 4: Custom Directive
If you prefer using a custom directive, Check Dan Dohotaru's answer which is an elegant solution implemented using ClipboardEvent
.
Solution 5: Angular Material
Angular material 9 + users can utilize the built-in clipboard feature to copy text. There are a few more customization available such as limiting the number of attempts to copy data.