【问题标题】:How to remove an event binding during run time in Angular? [duplicate]如何在运行时在 Angular 中删除事件绑定? [复制]
【发布时间】:2018-04-20 02:59:45
【问题描述】:

如何在 Angular 2+ 中从 div 中删除 foo() 处理程序?

<div #box (click)="foo($event)"></div>

这不起作用:

event.currentTarget.onclick = null

因为event.currentTarget.onclick 已经是null

也许,Angular 以不同的方式维护事件处理程序。

【问题讨论】:

  • 分享你的组件代码 box.nativeElement.onclick = null
  • 稍微更新了问题。我尝试简单的测试:foo(event: Event) { console.log(event.currentTarget.onclick); }。它返回null
  • 你能创建代码sn-p吗?
  • 如果目标是在第一次点击后移除事件绑定,那么它就是this question的副本。

标签: angular


【解决方案1】:

我不知道我是否可以帮助您删除绑定,但这样的事情可能会有所帮助:

在您的组件中:

removeBinding: boolean = false;

在您的 HTML 中:

<div #box (click)="!removeBinding ? (callMyFuncOnce(); removeBinding = true;): ''"></div>

【讨论】:

  • 这很好用,但我认为必须有一种方法可以在不创建额外“标志”变量的情况下实现结果。
  • 对!!只是看看渲染器是否有任何用处,我知道可以访问组件中的元素,但不知道如何删除侦听器。
  • 答案可能是in this post
猜你喜欢
  • 2015-11-28
  • 1970-01-01
  • 2016-07-28
  • 2015-07-26
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多