Stefan Stefan - 6 months ago 32
Javascript Question

Programmatically (un)register to event with Angular 2

I have a directive that listens to some events using the

host
property of the
@directive
decorator. This works great, but I don't need all events at all times.

For example, I'm only interested in
(document: mouseup)
at certain times (namely after a mousedown on my element).

What is the angular way to register and unregister to events dynamically?

Answer

If you register imperatively you can unregister the same way. AFAIK for declaratively added listeners there is no way to unregister.

import {DOM} from 'angular2/platform/common_dom.dart';

DOM
    .getGlobalEventTarget('window')
    .addEventListener('message', function, false);
    //.remove...

See also https://github.com/angular/angular/issues/6904

You could also just use

document.addEventListener
        // remove ...

but direct DOM access is discouraged. But in the comments of the linked issue they seem to see the first approach as direct DOM access as well.