Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How To Register an Event Listener on Document

DZone's Guide to

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 ·
Free Resource

Learn 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.

Topics:
angular 2 ,listener ,event

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}