gpt4 book ai didi

angular - 如何检测 mat-sidenav-container 中的滚动事件

转载 作者:太空狗 更新时间:2023-10-29 17:51:42 25 4
gpt4 key购买 nike

我不知道如何检测 mat-sidenav-container 何时在 Angular Material 2 中滚动。

我想在用户滚动时在我的组件上调用一个方法。但是,当使用 sidenav-container 时,滚动事件不再在窗口上触发。

取而代之的是一个额外的 <mat-sidenav-content cdkscrollable></mat-sidenav-content>添加了元素,这是滚动条所在的位置。如果我无法直接访问它以放置 (scroll)="myMethod()",我如何检测此组件何时发生滚动?事件监听器。

有什么想法吗?

最佳答案

您可以创建一个滚动事件的 Observable 并订阅它,而不是在每个滚动事件上调用一个方法。

使用可观察的

enum Direction {
Up = 'Up',
Down = 'Down'
}

ngAfterViewInit() {
const content = document.querySelector('.mat-sidenav-content');
const scroll$ = fromEvent(content, 'scroll').pipe(
throttleTime(10), // only emit every 10 ms
map(() => content.scrollTop), // get vertical scroll position
pairwise(), // look at this and the last emitted element
map(([y1, y2]): Direction => (y2 < y1 ? Direction.Up : Direction.Down)), // compare this and the last element to figure out scrolling direction
distinctUntilChanged(), // only emit when scrolling direction changed
share(), // share a single subscription to the underlying sequence in case of multiple subscribers
);

const goingUp$ = scroll$.pipe(
filter(direction => direction === Direction.Up)
);

const goingDown$ = scroll$.pipe(
filter(direction => direction === Direction.Down)
);

goingUp$.subscribe(() => console.log('scrolling up');
goingDown$.subscribe(() => console.log('scrolling down');
}

如需进一步了解上述代码,请查看: https://netbasal.com/reactive-sticky-header-in-angular-12dbffb3f1d3

关于angular - 如何检测 mat-sidenav-container 中的滚动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com