Stefan Stefan - 5 months ago 25x
Javascript Question

Programmatically (un)register to event with Angular 2

I have a directive that listens to some events using the

property of the
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?


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';

    .addEventListener('message', function, false);

See also

You could also just use

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