2017-10-10 92 views
1

我試圖在粘貼內容之後獲取文本輸入字段的內容。我如何獲取數據?我用的用於keyup事件的$event.target.value不適用。如果你粘貼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); 
    } 
} 
+1

'(ngModelChange)=「pasteEvent($ event)」'(發出所有更改,不僅粘貼) –

+0

Thanks @GünterZöchbauer,您的方法非常適合我的需求。如果您可以隨時創建答案,我會接受它。 – JohnDizzle

+0

謝謝,我更新了我的答案。 –

回答

1

如果你只是想在用戶的過去的東西的方式編輯值相同,以獲取模型更新,你可以使用

(ngModelChange)="pasteEvent($event)" 

或雙向綁定

[(ngModel)]="value" 

如果你真的要處理的過去的事件直接地說,事件應該有一個clipboardData屬性:

console.log($event.clipboardData); 

要獲得粘貼的文本,你可以使用getData

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

又見