Reputation: 621
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
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
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.
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));
}
Upvotes: 1
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