6
6
* found in the LICENSE file at https://angular.io/license
7
7
*/
8
8
9
- import { ElementRef , Injectable , NgZone , Optional , SkipSelf } from '@angular/core' ;
9
+ import { ElementRef , Injectable , NgZone , Optional , SkipSelf , OnDestroy } from '@angular/core' ;
10
10
import { Platform } from '@angular/cdk/platform' ;
11
11
import { Subject } from 'rxjs/Subject' ;
12
12
import { Subscription } from 'rxjs/Subscription' ;
@@ -26,7 +26,7 @@ export const DEFAULT_SCROLL_TIME = 20;
26
26
* Scrollable references emit a scrolled event.
27
27
*/
28
28
@Injectable ( )
29
- export class ScrollDispatcher {
29
+ export class ScrollDispatcher implements OnDestroy {
30
30
constructor ( private _ngZone : NgZone , private _platform : Platform ) { }
31
31
32
32
/** Subject for notifying that a registered scrollable reference element has been scrolled. */
@@ -97,14 +97,18 @@ export class ScrollDispatcher {
97
97
subscription . unsubscribe ( ) ;
98
98
this . _scrolledCount -- ;
99
99
100
- if ( this . _globalSubscription && ! this . _scrolledCount ) {
101
- this . _globalSubscription . unsubscribe ( ) ;
102
- this . _globalSubscription = null ;
100
+ if ( ! this . _scrolledCount ) {
101
+ this . _removeGlobalListener ( ) ;
103
102
}
104
103
} ;
105
104
} ) : observableOf < void > ( ) ;
106
105
}
107
106
107
+ ngOnDestroy ( ) {
108
+ this . _removeGlobalListener ( ) ;
109
+ this . scrollContainers . forEach ( ( _ , container ) => this . deregister ( container ) ) ;
110
+ }
111
+
108
112
/**
109
113
* Returns an observable that emits whenever any of the
110
114
* scrollable ancestors of an element are scrolled.
@@ -146,12 +150,20 @@ export class ScrollDispatcher {
146
150
return false ;
147
151
}
148
152
149
- /** Sets up the global scroll and resize listeners. */
153
+ /** Sets up the global scroll listeners. */
150
154
private _addGlobalListener ( ) {
151
155
this . _globalSubscription = this . _ngZone . runOutsideAngular ( ( ) => {
152
156
return fromEvent ( window . document , 'scroll' ) . subscribe ( ( ) => this . _scrolled . next ( ) ) ;
153
157
} ) ;
154
158
}
159
+
160
+ /** Cleans up the global scroll listener. */
161
+ private _removeGlobalListener ( ) {
162
+ if ( this . _globalSubscription ) {
163
+ this . _globalSubscription . unsubscribe ( ) ;
164
+ this . _globalSubscription = null ;
165
+ }
166
+ }
155
167
}
156
168
157
169
/** @docs -private */
0 commit comments