From 3e3394c92973986884f21e53a88bcf49969a8d4b Mon Sep 17 00:00:00 2001 From: zurfyx Date: Thu, 18 Jan 2018 20:11:00 +0100 Subject: [PATCH] scrolling view table implementation #2 --- src/contents-table.directive.ts | 29 +++++++++++++++++++++++++++-- src/contents.directive.ts | 2 +- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/contents-table.directive.ts b/src/contents-table.directive.ts index e213edd..9889866 100644 --- a/src/contents-table.directive.ts +++ b/src/contents-table.directive.ts @@ -3,7 +3,10 @@ import { ElementRef, HostListener, HostBinding, + Input, OnInit, + OnChanges, + OnDestroy, } from '@angular/core'; import { getAbsoluteHeight } from './html-utils'; @@ -12,23 +15,45 @@ import { getAbsoluteHeight } from './html-utils'; selector: '[contentsTable]', exportAs: 'contentsTable', }) -export class ContentsTableDirective implements OnInit { +export class ContentsTableDirective implements OnInit, OnChanges, OnDestroy { + @Input() scrollingView: HTMLElement; @HostBinding('class.sticky') sticky = false; @HostBinding('style.margin-top') marginTop = '0px'; + private scrollFun: EventListenerOrEventListenerObject = (event: Event) => this.updateStickiness(); + constructor( private elementRef: ElementRef, ) { } ngOnInit() { this.updateStickiness(); + this.unsubscribeScrollEventListener(); + this.subscribeScrollEventListener(); + } + + ngOnChanges() { + this.unsubscribeScrollEventListener(); + this.subscribeScrollEventListener(); + } + + ngOnDestroy() { + this.unsubscribeScrollEventListener(); + } + + // Subscribe to scrollingView scroll events. Sections will detectChanges() on scroll changes. + subscribeScrollEventListener() { + (this.scrollingView || document).addEventListener('scroll', this.scrollFun, false); + } + + unsubscribeScrollEventListener() { + (this.scrollingView || document).removeEventListener('scroll', this.scrollFun, false); } /** * Check whether the Table of Contents should be a sticky, to keep itself visible while the user * scrolls. */ - @HostListener('window:scroll', ['$event']) updateStickiness() { const pageOffset: number = window.pageYOffset; const parentElement: HTMLElement = this.elementRef.nativeElement.parentNode; diff --git a/src/contents.directive.ts b/src/contents.directive.ts index 776a871..f71ec3b 100644 --- a/src/contents.directive.ts +++ b/src/contents.directive.ts @@ -14,7 +14,7 @@ export class ContentsDirective implements OnInit, OnChanges, OnDestroy { _onScroll$: Subject = new Subject(); _activeSection$: BehaviorSubject = new BehaviorSubject(null); - scrollFun: EventListenerOrEventListenerObject = (event: Event) => this._onScroll$.next(event); + private scrollFun: EventListenerOrEventListenerObject = (event: Event) => this._onScroll$.next(event); constructor() { }