Over a million developers have joined DZone.

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.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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 !

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
angular 2 ,listener ,event

Published at DZone with permission of Juri Strumpflohner, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}