在(粘贴)事件后获取文本输入的值

Joh*_*zle 5 angular

在将某些内容粘贴到文本输入字段后,我试图获取它的内容。如何获取数据?我$event.target.value用于keyup事件的方法不起作用。如果您使用粘贴某些内容,则Ctrl + V由于keyup事件而起作用,但是,如果我尝试从浏览器的上下文菜单中粘贴某些内容,则它将不起作用。

这是一个非常简单的代码示例:

@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);
  }
} 
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 6

如果您只想在用户粘贴值时使用与编辑值相同的方式更新模型,则可以使用

(ngModelChange)="pasteEvent($event)"
Run Code Online (Sandbox Code Playgroud)

或双向绑定

[(ngModel)]="value"
Run Code Online (Sandbox Code Playgroud)

如果您实际上想直接处理过去的事件,则该事件应具有一个clipboardData属性:

console.log($event.clipboardData);
Run Code Online (Sandbox Code Playgroud)

要粘贴文本,可以使用getData

console.log($event.clipboardData.getData('Text'));
Run Code Online (Sandbox Code Playgroud)

也可以看看

  • 某种程度上,getData('Text')对我不起作用。我使用了(paste)=“ myMethod($ event.clipboardData.getData('text / plain'))” (2认同)