Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger keyup event in Angular 5 TypeScript

We have triggered keypress/down/up events programmatically easily with JavaScript/jQuery.

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

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')..........;
like image 959
Abdur Rahim Avatar asked Jan 23 '26 19:01

Abdur Rahim


1 Answers

In your app.component.html file, define events on DOM elements

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

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

}
like image 93
Sarthak Aggarwal Avatar answered Jan 26 '26 11:01

Sarthak Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!