5

Is there a way to copy html to clipboard in Angular?

I'm using ngx-clipboard, and trying to format the copied text (i.e., use bold, bullets)

.ts

constructor(private _clipboardService: ClipboardService) {}

callServiceToCopy() {
    this._clipboardService.copyFromContent('<B>This is an important message<\/B>\n These are the details');
}

Component:

<button class="btn btn-primary btn-sm" (click)="callServiceToCopy()">Copy</button>

Stackblitz: https://stackblitz.com/edit/github-ar12tp-irzz84

user749798
  • 4,872
  • 10
  • 46
  • 80
  • 1
    What do you mean by _format the copied text_ ? In your stackblitz example `callServiceToCopy()` function is working fine. I click on the button and the string was copied to my clipboard. Can you please elaborate your question. – HirenParekh Mar 30 '19 at 18:44

4 Answers4

0
copyToClipboard(id:string): void {
           const from = document.getElementById(id);
           const range = document.createRange();
           window.getSelection().removeAllRanges();
           range.selectNode(from);
           window.getSelection().addRange(range);
           document.execCommand('copy');
           window.getSelection().removeAllRanges();
 }

 <button (click)="copyToClipboard('<B>This is an important message<\/B>\n These are the details')">Copy text</button>
George C.
  • 5,637
  • 12
  • 49
  • 77
0

It doesn't use angular functionality, but here's what I use:

var dummy = document.createElement('input'),
  text = window.location.href;

document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
chuloon
  • 23
  • 4
0

.html

<div id="infoEd" role="textbox" aria-multiline="true" tabindex="2" contenteditable="true" (keyup)="" (keydown)="" (paste)="wrapContent($event)">
      </div>

.ts

   public wrapContent(evt) {
      const pastedData = evt.clipboardData.getData('html');
        console.log(pastedData);
    }

This Stackoverflow answer can help:- How do I copy to the clipboard in JavaScript?

Mahi
  • 3,396
  • 2
  • 30
  • 63
0

app.component.ts:

copyToClipboard(id:string): void {
  const fromHtml = this._elementRef.nativeElement.querySelector(id).innerHTML;
  const newNode = this.renderer.createElement('div');
  this.renderer.appendChild(this._elementRef.nativeElement, newNode);
  this.renderer.setProperty(newNode, 'innerHTML', fromHtml);
  this._clipboardService.copyFromContent(fromHtml);
}

app.component.html:

<textarea id="textId">This is a sample Text</textarea>
<button (click)="copyToClipboard('#textId')">Copy text</button>

Please check this StackBlitz: https://stackblitz.com/edit/github-ar12tp-scrwbn

Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
Prashanth
  • 119
  • 7