How To Register an Event Listener on Document
How To Register an Event Listener on Document
In this article, the author suggests a better way than directly accessing the document object and introduces the @HostListener decorator.
Join the DZone community and get the full member experience.
Join For FreeLearn how Crafter’s Git-based content management system is reinventing modern digital experiences.
I recently was asked by an Angular community member on Twitter how one can register an event on the document
object. While it is totally possible to directly access the document
object and hook up some listener, it is not suggested. There are better ways in Angular 2. See for yourself.
So, naively you could start and write something like this:
@Component({..})
export class MyComponent {
constructor() {
document.addEventListener('keyup', function() {
console.log('keys pressed');
});
}
}
This definitely works. However, it is considered bad practice to access elements outside the component directly such as in this case the global document
object.
So there are two possibilities.
Using the Component’s Host Property
You can use the component’s host property as follows:
import {KeyboardEvent} from '@angular/core';
@Component({
...
host: {
'(document:keyup)': 'onKeyUp($event)'
}
})
export class MyComponent {
onKeyUp(ev:KeyboardEvent) {
// do something meaningful with it
console.log(`The user just pressed ${ev.key}!`);
}
}
Using the @HostListener decorator
Alternatively — and personally my preferred way of doing it — is to use the @HostListener
decorator:
import {HostListener, KeyboardEvent} from '@angular/core';
@Component({...})
export class MyComponent {
@HostListener('document:keyup', ['$event'])
onKeyUp(ev:KeyboardEvent) {
// do something meaningful with it
console.log(`The user just pressed ${ev.key}!`);
}
}
Try It Yourself
Here’s a Plunker to play around with: https://plnkr.co/edit/n20EtGiB9trW0M5EkIfH?p=preview
Hope this was helpful !
Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.
Published at DZone with permission of Juri Strumpflohner . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}