【问题标题】:Copy html to clipboard (Angular)将 html 复制到剪贴板 (Angular)
【发布时间】:2019-04-06 17:55:08
【问题描述】:

有没有办法在 Angular 中将 html 复制到剪贴板?

我正在使用 ngx-clipboard,并尝试格式化复制的文本(即使用粗体、项目符号)

.ts

constructor(private _clipboardService: ClipboardService) {}

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

组件:

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

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

【问题讨论】:

  • 格式化复制的文本是什么意思?在您的 stackblitz 示例中,callServiceToCopy() 函数运行良好。我单击按钮,字符串被复制到我的剪贴板。您能否详细说明您的问题。

标签: angular clipboard


【解决方案1】:
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>

【讨论】:

【解决方案2】:

它不使用角度功能,但这是我使用的:

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);

【讨论】:

  • 谢谢,但正在寻找角度响应。
【解决方案3】:

.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);
    }

这个 Stackoverflow 答案可以提供帮助:- How do I copy to the clipboard in JavaScript?

【讨论】:

    【解决方案4】:

    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>
    

    请查看此 StackBlitz:https://stackblitz.com/edit/github-ar12tp-scrwbn

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多