在Angular 5 TypeScript中如何触发keyup事件

3
我们可以使用JavaScript/jQuery轻松地以编程方式触发keypress/down/up事件。
$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

但是使用Angular 5和TypeScript,我们该怎么做呢?
//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')..........;

3
直接使用 Document API 访问 DOM 不是一个好的实践。也不建议使用 jQuery。Angular 有自己的方法来处理这个问题。可以使用 (click) 事件代替。例如:<div (click)="eventHandler()"></div> - SiddAjmera
你可以让事件直接写在元素上吗? - Jignesh M. Khatri
@SiddAjmera 由于输入框具有“KeyUp”事件,因此我想触发它。我知道可以调用(click)并调用由KeyUp调用的函数。请告诉我是否有一种方法可以调用它。 - Abdur Rahim
3个回答

17

在您的app.component.html文件中,定义DOM元素上的事件

<input (keyup)="onKeyup($event)" (keydown)="onKeydown($event)" #userName></input>

在您的 app.component.ts 文件中,获取元素引用并分派事件,还要为相同的事件创建事件处理程序。

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)
 }

}

该事件已绑定。但是从另一个角度,我想以编程方式触发(keyup)事件。 - Abdur Rahim
KeyboardEvent 构造函数不支持 IE。 - r0bb077

2
如果你想在HTML中监听Angular事件,可以像这样操作:
<button (click)="eventHandler($event)">

在组件的TypeScript类中,您有一个方法:

eventHandler(event){
  console.log(event);
}

这是最常见的方法。

在Angular中,你也可以获取元素引用。首先,在元素上添加 #value:

<button #myButton>
< p > #MyButton 语法允许您使用 @ViewChild 元数据在代码中引用子组件:

@ViewChild('myButton')
myButton: ElementRef;

然后你应该能够调用本地元素上的方法:
myButton.nativeElement.keydown();
myButton.nativeElement.keypress();
myButton.nativeElement.keyup();
myButton.nativeElement.blur();

实际上我并没有测试过这个,因为在Angular中,很少尝试访问底层DOM事件,而是使用Angular对它们的封装。


出现了“Uncaught TypeError: ...nativeElement.keyup is not a function”错误。 - Jeb50
那个语法看起来不对,也许你需要像这样 keyup.addEventListener('keyup', handlerfunction); 的东西。 - JeffryHouser
好的,感谢您。 - Jeb50

2

这与JavaScript和TypeScript无关,TypeScript基本相同。区别在于jQuery和Angular。

给你的按钮标上一个id,这样我们就可以从组件中访问它。

<button #submitButton ...>

在你的组件中,你可以使用ViewChild装饰器来访问这个元素。
export class FooComponent {
    @ViewChild('submitButton')
    submitButtonRef: ElementRef;

    emitClick() {
         // ...
    }
}

然后要触发点击,您可以执行以下操作:
emitClick() {
    this.submitButtonRef.nativeElement.click();
}

请确保不要过早调用emitClick。如果我没有记错,ViewRef仅在AfterViewInit Angular生命周期事件之后才可用。

对于焦点,这也应该有效。其他事件可能会有些棘手,但您拥有本机dom元素,因此基本上只需要找出如何在没有jquery的情况下在本机dom元素上触发所需的事件即可。如果您需要,可以参考此答案:trigger custom event without jQuery


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接