[英]Why are Angular Keystrokes not run synchronously? Or how can I make them run synchronously?
How can I make Angular 4/2 keystroke events run synchronously? 如何使Angular 4/2击键事件同步运行? When I run this code the keys are not always run in order of firing.
当我运行此代码时,键并不总是按触发顺序运行。
Template 模板
<div
contenteditable="true"
(keydown)="divKeyDown($event)"
(keyup)="divKeyUp($event)">
</div>
Component 零件
divKeyDown(event) {
console.log('Keydown');
// OFTEN GETS FIRED BEFORE KEYUP OF PREVIOUS STROKE
}
divKeyUp(event) {
console.log('Keyup');
}
Keyup is only fired when the key has literally become up and has no concern of other keystrokes. 仅当按键从字面上升起并且不关心其他击键时才触发Keyup。
Keypress would be a better event to use in this scenario as it is always fired directly after keydown, and never before another keystroke. 在这种情况下,使用按键会是一个更好的选择,因为它总是在按键后立即触发,而不是在其他按键之前触发。
This is default behavior and not related directly to Angular. 这是默认行为,与Angular没有直接关系。
Even in vanilla JS, the same behavior is observed: 即使在普通JS中,也会观察到相同的行为:
document.getElementById('main').addEventListener('keydown', event => {
console.log('keydown'); // FIRED ONCE
});
document.getElementById('main').addEventListener('keypress', event => {
console.log('keypress'); // FIRED AFTER KEYDOWN
});
document.getElementById('main').addEventListener('keyup', event => {
console.log('keyup'); // FIRED WHEN THE KEY HAS LITERALLY BEEN RELEASED
});
(In this scenario I have used Angular's 'ngAfterViewChecked' lifecycle hook to handle the changes in state directly after the 'keydown' event has completed) (在这种情况下,我已使用Angular的'ngAfterViewChecked'生命周期挂钩在'keydown'事件完成后立即处理状态更改)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.