1

OK, so this might have already been asked and answered, but I couldn't find it. In my HTML, I have declared a listener to the window.scroll event. Since this is only declared in my HTML,

  1. is there a way to unbind the scroll event? Can I do it through ngOnDestroy()? If so, how?
  2. OR is it safe to not unbind it and assume that NG2 will clean up the mess when the component is destroyed?

I'm using Angular2 RC.1.

My HTML:

<div (window:scroll)="bindToScrollEventFunc()"></div>

I'm a little worried that if the component is destroyed, the listening function will still be around in memory and cause problems if it is not unbound. Any info on the matter is greatly appreciated! TIA!

hartpdx
  • 2,230
  • 2
  • 15
  • 18
  • You can't. See [here](http://stackoverflow.com/questions/35314212/programmatically-unregister-to-event-with-angular-2/35314254#35314254) – drew moore Jun 03 '16 at 23:42

1 Answers1

0
  1. @drewmoore already referenced in a comment @Günter's answer: "for declaratively added listeners there is no way to unregister".

  2. Angular will unregister any/all event listeners it added when the component is destroyed.
    Let's think about this... if Angular didn't do this, it would cause serious memory leaks in large applications. And Angular is targeted at large apps with multiple developers.

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • Thanks for the answer! I agree with your second bullet, and that is what I would expect. I guess one thing I didn't qualify in my question was that the event is bound to the **window** from the component. Do you think the same still holds true? Is NG2 smart enough to unregister events bound to the window? – hartpdx Jun 06 '16 at 15:54
  • @hartpdx, yes, I believe the same still holds true. – Mark Rajcok Jun 06 '16 at 16:54