Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- Directive,
- EventEmitter,
- HostListener,
- Output,
- OnInit,
- OnDestroy,
- } from '@angular/core';
- import { Subject, Subscription } from 'rxjs';
- import { distinctUntilChanged } from 'rxjs/operators';
- @Directive({
- selector: '[pxcScrollTop]'
- })
- export class ScrollTopDirective implements OnInit, OnDestroy {
- @Output() public displayElement = new EventEmitter<boolean>();
- showButton: Subject<boolean> = new Subject();
- subs: Subscription[] = [];
- constructor() { }
- @HostListener('window:scroll', ['$event']) public windowScrolled($event: Event) {
- this.windowScrollEvent($event);
- }
- @HostListener('click') click() {
- window.scrollTo({
- top: 0,
- behavior: 'smooth',
- });
- }
- ngOnInit(): void {
- this.showButton.pipe(
- distinctUntilChanged()
- ).subscribe((x) =>
- this.displayElement.emit(x)
- );
- }
- ngOnDestroy() {
- this.subs.forEach(sub => sub.unsubscribe());
- }
- protected windowScrollEvent($event: Event) {
- const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
- this.showButton.next(scrollTop > 1000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement