7

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);
  }
} 
JohnDizzle
  • 1,268
  • 3
  • 24
  • 51

2 Answers2

10

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Somehow the getData('Text') didn't work for me. I used (paste)="myMethod($event.clipboardData.getData('text/plain'))" – Olivier Tonglet Jul 11 '18 at 09:04
  • @Gunter, when you say or two way binding, what is the proper way to check cilpboard value using the shortcut: [(ngModel)]="value"? – Janatbek Orozaly Jun 05 '19 at 13:18
  • @JanatbekSharsheyev `[(...)]` is the closest to 2-way binding in Angular and only related for input/output combinations and not related to the clipboard or such. – Günter Zöchbauer Jun 05 '19 at 13:20
3

for me below code worked :

(paste)="onPasteHandler($event.clipboardData.getData('text/plain'))"
MD Ashik
  • 9,117
  • 10
  • 52
  • 59
soni kumari
  • 313
  • 4
  • 4