I've started looking into Angular2 and have a basic up with 3 nested componenets working. However I cannot work out how to add a keypress handler to the document.
If not, how would I listen for a keypress on the document and react to it? To be clear I need to respond to a kepyress on the document itself, NOT an input.
In Angular 1 I would create a directive and use $document; something like this:
$document.on("keydown", function(event) {
// if keycode...
event.stopPropagation();
event.preventDefault();
scope.$apply(function() {
// update scope...
});
But I have yet to find an Angular2 solution.
You can do something like this:
@Component({
host: {
'(document:keyup)': '_keyup($event)',
'(document:keydown)': '_keydown($event)',
},
})
export class Component {
private _keydown(event: KeyboardEvent) {
let prevent = [13, 27, 37, 38, 39, 40]
.find(no => no === event.keyCode);
if (prevent) event.preventDefault();
}
private _keyup(event: KeyboardEvent) {
if (event.keyCode === 27) this.close();
else if (event.keyCode === 13) ...;
else if (event.keyCode === 37) ...;
else if (event.keyCode === 38) ...;
else if (event.keyCode === 39) ...;
else if (event.keyCode === 40) ...;
// else console.log(event.keyCode);
}
}
BTW, Angular team had some interesting ideas about keyboard events, not sure what's the status of this at the moment. It's even possible it's working, didn't try myself :)
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