Search code examples
angulartypescriptinternet-explorer-11copy-paste

IE 11 Paste only works on Input Fields


I need to capture the paste event on a custom grid however in IE11 the Ctrl + V paste event only works on Input Fields. I need it to work on a component and access it via the Window. In Chrome it works perfect.

 public ngOnInit() {
   window.addEventListener('paste', myCustomEvent.bind(this));
}

In Chrome when user clicks Ctrl+ V anywhere on the screen this fires

myCustomEvent(event) {    

    // gets data from clipboard and converts it to an array (1 array element for each line)
    let clipboardData = event.clipboardData || event.originalEvent['clipboardData'].getData('text');
    console.log('event' , event);
    console.log(clipboardData);
}

Solution

  • Create a listener event for keydown. When the user presses Ctrl+V it will fire your event. From there you can access the clipBoardData. Dont forget to import Renderer2 into your constructor

    this.global = this.renderer.listen('document', 'keydown', (event) => {
            if (event.ctrlKey === true && event.key === 'v') {
              const clipboardData = window['clipboardData'].getData('Text');
              if (clipboardData) {
                this.ProcessBeforePaste(clipboardData);
              }
            }
          });