Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - On Paste Event Get Content

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.

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> 

Component

  /**    * 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)   } 

Question How 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?

like image 296
SBB Avatar asked May 02 '18 16:05

SBB


People also ask

What is ng paste?

The ng-paste directive tells AngularJS what to do when text is pasted into an HTML element. The ng-paste directive from AngularJS will not override the element's original onpaste event, both will be executed.

How do I disable paste in HTML?

You can disable cut, copy, and paste using the oncut, oncopy, and onpaste event attributes with the target HTML elements. If you want to disable cut, copy, and paste for the complete web page, you need to use these event attributes with the body tag.


1 Answers

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> 

with this code:

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

See this stackblitz for a demo.

like image 104
ConnorsFan Avatar answered Sep 23 '22 09:09

ConnorsFan