3

I'm trying to create two scroll event observable for both scroll direction vertical and horizontal.

I tried using pairwise() and bufferCount(2,1) operators to filter vertical scroll event from the horizontal one, but the problem is with getting duplicate values for prev.scrollTop and curr.scrollTop

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
import { pairwise, tap, filter } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  @ViewChild('scrollable', {static: false}) scrollable: ElementRef;


  ngAfterViewInit() {

    fromEvent(this.scrollable.nativeElement, 'scroll').pipe(
      pairwise(),
      tap(([prev, curr]) => console.log(prev.target.scrollTop, curr.target.scrollTop)),
      filter(([prev, curr]) => prev.target.scrollTop !== curr.target.scrollTop),
      tap((e) => console.log(e)) // <=    Never reached
    ).subscribe();

  }

}

Any ideas?

stackblitz reproduction

Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185

1 Answers1

6

that's because you pairwised the nativeElement, which is always referencing the same object. So basically you have to pluck your desire primitive value.

  fromEvent(this.scrollable.nativeElement, 'scroll').pipe(
      pluck('target','scrollTop'),
      pairwise(),
      tap(([prev, curr]) => console.log(prev,curr)),
      filter(([prev, curr]) => prev!== curr),
      tap((e) => console.log(e)) // <=    Never reached
    ).subscribe();
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
  • This throws Error: Cannot read property 'scrollTop' of undefined, can you try your solution with the stackblitz https://stackblitz.com/edit/angular-5zqlsj – Murhaf Sousli Jun 11 '19 at 02:04
  • 1
    try this https://stackblitz.com/edit/angular-3w6vrh?file=src/app/app.component.ts – Fan Cheung Jun 11 '19 at 02:06