Paste事件获取内容

Paste事件获取内容

本文介绍了Angular - On Paste事件获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角度组件,允许用户将数据输入 textarea 。有两个事件绑定到此 keydown 粘贴。这两个事件都会触发相同的方法来尝试确定输入的数据。

I have an angular component that allows a user to enter data into a textarea. There are two events tied to this keydown and paste. Both of these events trigger the same method which will try and determine the data entered.

我遇到的问题是粘贴数据时粘贴,我得到的是 formControl 的值,但它的值是在粘贴数据之前的值,而不包括我实际输入的数据字段。

The issue I am having is when the data is pasted paste, I am getting the value of the formControl but its the value BEFORE the data is pasted and doesn't include what I actually just entered into the field.

HTML

<textarea
  formControlName="multiSearch"
  class="form-control"
  placeholder="Enter one or more values. One per line."
  rows="6"
  (keydown)="keyDownFunction($event)"
  (paste)="onPaste()">
</textarea>

组件

  /**
   * If we hit enter in our text area, determine the data type
   */
  keyDownFunction(event) {

    // Enter Key?
    if (event.keyCode == 13) {
      this.determineDataType();
    }
  }

  /**
   * If we paste data in our text area, determine the data type
   */
  onPaste() {
    this.determineDataType();
  }

  /**
   * Using regex, determine the datatype of the data and confirm with the user.
   */
  determineDataType() {
    console.log(this.searchForm.value.multiSearch)
  }

问题
如何在后立即访问粘贴到表单中的数据粘贴事件被触发而不是粘贴之前的值是什么?

QuestionHow can I get access to the data that is pasted into the form as soon as the paste event is fired and not what the value was before pasting?

推荐答案

你可以获得粘贴来自粘贴事件的内容以及 textarea 的更新内容,通过处理输入事件:

You can get the pasted content from the paste event and the updated content of the textarea by handling the input event:

<textarea #myText (paste)="onPaste($event)" (input)="onInput(myText.value)"></textarea>

使用此代码:

onPaste(event: ClipboardEvent) {
  let clipboardData = event.clipboardData || window.clipboardData;
  let pastedText = clipboardData.getData('text');
  ...
}

onInput(content: string) {
  ...
}

请参阅演示。

See this stackblitz for a demo.

这篇关于Angular - On Paste事件获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:06