在Angular 5 TypeScript中触发keyup事件 [英] Trigger keyup event in Angular 5 TypeScript
本文介绍了在Angular 5 TypeScript中触发keyup事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们已经使用JavaScript/jQuery以编程方式轻松触发了按键/按下/按下事件.
We have triggered keypress/down/up events programmatically easily with JavaScript/jQuery.
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
但是使用Angular 5和TypeScript,我们该怎么做?
But with Angular 5 and TypeScript, how can we do that?
//I am setting value programmatically -> working
document.getElementById('custom_Credit').setAttribute('value', coinsToBuy);
//setting focus -> working
document.getElementById('custom_Credit').focus();
//but there are no way to generate or trigger keypress/up events.
document.getElementById('custom_Credit')..........;
推荐答案
在app.component.html文件中,定义DOM元素上的事件
In your app.component.html file, define events on DOM elements
<input (keyup)="onKeyup($event)" (keydown)="onKeydown($event)" #userName></input>
在您的app.component.ts文件中,获取元素ref并调度一个事件,还为该事件创建事件处理程序
In your app.component.ts file , get element ref and dispatch an event, also make event handlers for the same
export class AppComponent {
@ViewChild('userName') userInput: ElementRef;
constructor() {}
someFunction(){
let event = new KeyboardEvent('keyup',{'bubbles':true});
this.userInput.nativeElement.dispatchEvent(event);
}
onKeyup(event){
console.log(event)
}
onKeydown(event){
console.log(event)
}
}
这篇关于在Angular 5 TypeScript中触发keyup事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文