Skip to content

Commit

Permalink
scrolling view table implementation #2
Browse files Browse the repository at this point in the history
  • Loading branch information
zurfyx committed Jan 18, 2018
1 parent d6de9e5 commit e192471
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
29 changes: 27 additions & 2 deletions src/contents-table.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import {
ElementRef,
HostListener,
HostBinding,
Input,
OnInit,
OnChanges,
OnDestroy,
} from '@angular/core';

import { getAbsoluteHeight } from './html-utils';
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/contents.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class ContentsDirective implements OnInit, OnChanges, OnDestroy {
_onScroll$: Subject<Event> = new Subject<Event>();
_activeSection$: BehaviorSubject<String> = new BehaviorSubject<String>(null);

scrollFun: EventListenerOrEventListenerObject = (event: Event) => this._onScroll$.next(event);
private scrollFun: EventListenerOrEventListenerObject = (event: Event) => this._onScroll$.next(event);

constructor() { }

Expand Down

0 comments on commit e192471

Please sign in to comment.