Angular 6-复制到移动版剪贴板(IOS,Android)

时间:2019-06-19 03:07:13

标签: javascript angular

此案例explains如何使用angular 5实现复制到剪贴板,但我发现它无法在iphone 6s上成功运行。有更完整的解决方案吗?

1 个答案:

答案 0 :(得分:0)

一种方法是创建一个范围并将该范围添加到选择(stackblitz

@HostListener("click", ["$event"])
  public onClick(event: MouseEvent): void {
    event.preventDefault();
    if (!this.payload)
      return;

    var range = document.createRange();
    range.selectNodeContents(document.body);
    document.getSelection().addRange(range);

    let listener = (e: ClipboardEvent) => {
      let clipboard = e.clipboardData || window["clipboardData"];
      clipboard.setData("text", this.payload.toString());
      e.preventDefault();
      this.copied.emit(this.payload);
    };

    document.addEventListener("copy", listener, false)
    document.execCommand("copy");
    document.removeEventListener("copy", listener, false);

    document.getSelection().removeAllRanges();
  }