Finn
Finn

Reputation: 1459

Angular 6 - Copy to clipboard for mobile (IOS, Android)

This case explains how to use angular 5 implementation to copy to clipboard, but I found that it can't run successfully on the iphone 6s. Is there a more complete solution?

Upvotes: 0

Views: 986

Answers (1)

Dan Dohotaru
Dan Dohotaru

Reputation: 3089

One approach would be to create a range and add that range to the selection (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();
  }

Upvotes: 1

Related Questions