2

In my Angular app, I am trying to detect what a user cut from a text input. I am able to detect the clipboard data in a paste event, but the cut and copy events do not show the clipboard data. Is there a different approach to inspect cut and copy events?

HTML:

<input [(ngModel)]='code' #codeInput="ngModel" 
    (copy)=clipboardEvent($event) 
    (cut)=clipboardEvent($event) 
    (paste)=clipboardEvent($event)>

TS:

    clipboardEvent(event: ClipboardEvent){        
        let clipboardData = event.clipboardData;
        let clipboardText = clipboardData.getData('text');
        console.log('clipboard text: ', clipboardText);
    }

Demo: https://stackblitz.com/edit/angular-clipboard-data

Eric Soyke
  • 1,073
  • 1
  • 15
  • 30
  • You can try creating a ```HostListener``` for each event in a directive and use that on your input. Similar example: https://stackoverflow.com/a/47385485/9901630 – nll_ptr Sep 16 '19 at 19:18
  • @nullptr.t that just creates the same problem for me. I tried and it has the exact same result when querying the event- the clipboardData is only returned for a paste. – Eric Soyke Sep 16 '19 at 19:39

1 Answers1

1

A different approach must be used for cut/copy versus paste. Reference window for cut/copy rather than the event:

TS:

    pasteEvent(event: ClipboardEvent){  
        let clipboardText = event.clipboardData.getData('text');        
        console.log(clipboardText);
    }
    cutCopyEvent(){  
        let clipboardText = window.getSelection().toString();        
        console.log(clipboardText);
    }

Demo (fixed): https://stackblitz.com/edit/angular-clipboard-data-rvphn8

Eric Soyke
  • 1,073
  • 1
  • 15
  • 30