问题
Working on an Angular / TypeScript app, where we have a custom basic text editor.
Trying to appropriately handle when a user has a highlighted selection and then hits a key, intending to replace the selection.
To handle this, we need to properly remove the "hidden" components that they have selected before inserting their intended content.
My initial thought was to:
- Capture KeyDown event
- Check if there is a highlighted range selected
- If yes, delete all of the selected content
- Re-dispatch the KeyDown event so it inserts the appropriate content
Here's a truncated version of our onKeyDown
method:
cloneKeyboardEvent(eventToClone): KeyboardEvent {
return new KeyboardEvent(eventToClone.type, {
key: eventToClone.key,
code: eventToClone.code,
location: eventToClone.location,
ctrlKey: eventToClone.ctrlKey,
shiftKey: eventToClone.shiftKey,
altKey: eventToClone.altKey,
metaKey: eventToClone.metaKey,
repeat: eventToClone.repeat
});
}
onKeyDown($event: KeyboardEvent) {
// Check if there's a selection
if (this.isSelectionRange) {
Helpers.stopEvent($event);
// Delete components in selection
this.deleteComponentsInSelection($event);
const clonedEvent = this.cloneKeyboardEvent($event);
document.dispatchEvent(clonedEvent);
return true;
}
}
Everything works up to #4.
The clonedEvent
matches the original event, but it won't fire. I've inserted a debugger
at the start of onKeyDown()
and it only is hit once, on the initial keydown, not on the dispatchEvent()
.
来源:https://stackoverflow.com/questions/47060630/re-dispatch-keyboardevent