Last active
April 16, 2019 20:12
-
-
Save FelixEhuan/d2ccf2d4fab0cb6db62c55fda9bdf646 to your computer and use it in GitHub Desktop.
Sticky element directive, the input it's a offset distance of the element from top
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, Renderer2, ElementRef, HostListener, Input, OnInit } from '@angular/core'; | |
import { ActivatedRoute } from '@angular/router'; | |
import { Observable } from 'rxjs'; | |
import { Router, NavigationStart } from '@angular/router'; | |
import { filter } from 'rxjs/operators'; | |
@Directive({ | |
selector: '[Sticky-Element]' | |
}) | |
export class StickyElementDirective implements OnInit { | |
private initialOffsetFromTop = 0; | |
private fixedViewportOffset = 0; | |
private observable_data: any; | |
private url: boolean; | |
navStart: Observable<NavigationStart>; | |
@Input() offset: number; | |
constructor(private element: ElementRef, private renderer: Renderer2, private route: ActivatedRoute, private router: Router) { | |
route.url.subscribe(data => { this.observable_data = data; }); | |
this.navStart = router.events.pipe(filter(evt => evt instanceof NavigationStart)) as Observable<NavigationStart>; | |
} | |
ngOnInit() { | |
// This validation if for navbar toogling only on the root view, remove if necessary | |
this.navStart.subscribe(evt => { | |
evt.url === '/' ? this.url = true : this.url = false; | |
if (evt.url !== '/') { | |
this.renderer.removeClass(this.element.nativeElement, 'transparent'); | |
} else { | |
this.renderer.addClass(this.element.nativeElement, 'transparent'); | |
} | |
}); | |
} | |
@HostListener('window:scroll', ['$event']) | |
// The navbar must be solid and a class named transparent is added, otherwhise switch the addClass and removeClass | |
private handleScroll($event: Event) { | |
const currentScroll = $event.srcElement.children[0].scrollTop; | |
if (currentScroll < this.offset && this.url) { | |
this.renderer.addClass(this.element.nativeElement, 'transparent'); | |
} else if (this.offset < currentScroll) { | |
this.renderer.removeClass(this.element.nativeElement, 'transparent'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment