使用Angular 2以编程方式(un)注册事件 [英] Programmatically (un)register to event with Angular 2
问题描述
我有一个指令,使用 @directive
装饰器的主机
属性来侦听某些事件。这很好用,但我不需要所有的事件。
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.
例如,我只对感兴趣(文件:mouseup )
在某些时候(即我元素上的mousedown之后)。
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?
推荐答案
如果您必须注册,则可以以相同的方式取消注册。 AFAIK用于声明性添加的侦听器,无法取消注册。
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...
参见 https://github.com/angular/angular/issues/6904
您也可以使用
document.addEventListener
// remove ...
但不鼓励直接访问DOM。但在链接问题的评论中,他们似乎也将第一种方法视为直接DOM访问。
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.
这篇关于使用Angular 2以编程方式(un)注册事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!