Search code examples
angulartypescriptgmailclipboardpaste

Detect line split from gmail in clipboard (angular)


I'm trying to allow users to paste from gmail into a field, and detect line breaks. It does not need to be a text area, I just want to detect the line breaks.

The problem is that when a user pastes something like below...clipboard does not seem to detect the break (even if user had hit enter in gmail)

Item 1 
Item 2 
Item 3

To detect it, the user seems to have to have hit enter twice...like below:

Item 1

Item 2

Item 3

Is there a way to detect line breaks from gmail?

Below seems to work for notepad, inbox and other areas where I copy from.

Stackblitz Demo

Component:

<input type="text" placeholder="paste items here" (paste)="onPaste(i, $event, $event)">

<div *ngIf="itemArray.length > 0">
Item list:
</div>

<div *ngFor="let item of itemArray">
  {{item}}
</div>

TS:

itemArray = [];

  onPaste(i, event: ClipboardEvent, value) {
    let clipboardData = event.clipboardData;
    let pastedText = clipboardData.getData('text/plain').split("\n");
    pastedText.forEach(item => {
      item = item.toString()
      item = item.replace(/(\r\n|\n|\r|\s\r|\r)/gm, "")
      this.itemArray.push(item) 
    })
  }

Solution

  • I think the problem is that the pasted text has line breaks that are just carriage return (\r). This is not transported into an input field. Looks like just \n is passing. I found an approach that uses a textarea which takes over the line feeds independent on \r or \n or \r\n. Then use the input event of the textarea to read the text from it. So it is a kind of proxy for the clipboard. I know this is not a proper solution but may help a little.

    I have modified your Stackblitz.