在 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屋!
查看全文