Advertisement
xapu

Untitled

Oct 1st, 2018
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. import {
  2. Directive,
  3. EventEmitter,
  4. HostListener,
  5. Output,
  6. OnInit,
  7. OnDestroy,
  8. } from '@angular/core';
  9. import { Subject, Subscription } from 'rxjs';
  10. import { distinctUntilChanged } from 'rxjs/operators';
  11.  
  12. @Directive({
  13. selector: '[pxcScrollTop]'
  14. })
  15. export class ScrollTopDirective implements OnInit, OnDestroy {
  16.  
  17. @Output() public displayElement = new EventEmitter<boolean>();
  18.  
  19. showButton: Subject<boolean> = new Subject();
  20.  
  21. subs: Subscription[] = [];
  22.  
  23. constructor() { }
  24.  
  25. @HostListener('window:scroll', ['$event']) public windowScrolled($event: Event) {
  26. this.windowScrollEvent($event);
  27. }
  28.  
  29. @HostListener('click') click() {
  30. window.scrollTo({
  31. top: 0,
  32. behavior: 'smooth',
  33. });
  34. }
  35.  
  36. ngOnInit(): void {
  37. this.showButton.pipe(
  38. distinctUntilChanged()
  39. ).subscribe((x) =>
  40. this.displayElement.emit(x)
  41. );
  42. }
  43.  
  44. ngOnDestroy() {
  45. this.subs.forEach(sub => sub.unsubscribe());
  46. }
  47.  
  48. protected windowScrollEvent($event: Event) {
  49. const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  50.  
  51. this.showButton.next(scrollTop > 1000);
  52. }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement