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')..........;
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With