Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value of Text Input after (paste) Event

Tags:

angular

I´m trying to get the content of a text input field after something was pasted inside it. How can I fetch the data? My approach with $event.target.value I used for the keyup event doesn't work. If you paste something with Ctrl + V It works due to the keyup event, but if I try to paste something from the context menu of the browser it doesn´t work.

Here is a very simple Code sample:

@Component({
  selector: 'my-app',
  template: `<input type="text" [ngModel]="value" (paste)="pasteEvent($event)" (keyup)="keyupEvent($event)">
  <br>{{result}}`
})
export class AppComponent {
  public result: string;

  public pasteEvent($event: any) {
    this.result = $event.target.value;
    console.log('paste: '+ $event.target.value);
    console.log($event);
  }

  public keyupEvent($event: any) {
    this.result = $event.target.value;
    console.log('keyup: '+ $event.target.value);
  }
} 
like image 607
JohnDizzle Avatar asked Oct 10 '17 07:10

JohnDizzle


2 Answers

If you just want to get the model updated when the user pasts something the same way as editing the value, you can just use

(ngModelChange)="pasteEvent($event)"

or two-way binding

[(ngModel)]="value"

If you actually want to handle the past event directly, the event should have a clipboardData property:

console.log($event.clipboardData);

To get pasted text, you can use getData:

console.log($event.clipboardData.getData('Text'));

See also

  • JavaScript get clipboard data on paste event (Cross browser)
  • https://developer.mozilla.org/en-US/docs/Web/Events/paste
like image 176
Günter Zöchbauer Avatar answered Oct 24 '22 09:10

Günter Zöchbauer


for me below code worked :

(paste)="onPasteHandler($event.clipboardData.getData('text/plain'))"
like image 31
soni kumari Avatar answered Oct 24 '22 09:10

soni kumari