Harry
Harry

Reputation: 621

Click button doing the same as the CTRL-V event

I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>

Upvotes: 0

Views: 759

Answers (2)

YounesM
YounesM

Reputation: 2317

They're not the same events: When you click a MouseEvent is emitted, when you use ctrl+v a ClipboardEvent event is emitted. MouseEvent does not have clipbordData param, thus your error.

enter image description here

To get access to the clipboard on click you'll need to use the Clipboard API that will ask for access permissions.

  onPaste(e: ClipboardEvent) {
    console.log(e);
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
  }

  clickPaste() {
    navigator.clipboard.readText().then(clipboard => alert(clipboard));
  }

Stackblitz

Upvotes: 1

Anand Bhushan
Anand Bhushan

Reputation: 783

On CTRL-V you get event of type ClipboardEvent which has clipboardData on it. While your click event is of type MouseEvent which has no clipboardData on it.

I've created a stackblitz demo to reproduce it , you can try for yourself.

Upvotes: 0

Related Questions