How to get triggered on scrolling inside cdk-virtual-scroll-viewport?
The way for listening to scroll events within CdkVirtualScrollViewport
is using elementScrolled()
method:
this.virtualScroll.elementScrolled()
.subscribe(event => {
console.log('scrolled');
});
So there is no need to inject scrollDispatcher
and register any element...
smartmouse
Considerable experience in web applications development, both as front-end developer and as CMS webmaster. Bitcoin and blockchain enthusiast as writer, speaker and developer of personal projects. An effective communicator with good leadership and analytical skills. Seeking new challenges and responsibilities to progress career. Spare time is for reading news, traveling and working on new ideas...
Updated on June 04, 2022Comments
-
smartmouse almost 2 years
I'm using virtual scroll with Angular 7. I create a
CdkVirtualScrollViewport
and I would add a listener to every scroll event. I mean I would like to be notified on scrolling inside that viewport.I tried to inject
scrollDispatcher
in my component, but I see thatscrolled()
is triggered on scrolling on the whole component, then I figure out that it is bind to the component instead of just toCdkVirtualScrollViewport
.Here is my code:
@ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport; items: Array<any>; constructor(private scrollDispatcher: ScrollDispatcher, private cd: ChangeDetectorRef) { this.items = []; } ngOnInit(): void { for (let i = 0; i < 100; i++) { this.items.push(i); } } ngAfterViewInit(): void { this.scrollDispatcher.scrolled() .subscribe(event => { console.log('scrolled'); }); }
As you can see
CdkVirtualScrollViewport
is a child element inside my component:<div class="header"> {{header}} </div> <div class="container"> <cdk-virtual-scroll-viewport itemSize="4" class='example-viewport'> <li *cdkVirtualFor="let item of items" class='example-item' >{{item}}</li> </cdk-virtual-scroll-viewport> </div> <div class="footer"> {{footer}} </div>
Here is the full code: https://stackblitz.com/edit/angular7-scroll-dispatcher
Maybe I could use
register()
method ofscrollDispatcher
... but I should pass aCdkScrollable
to it, instead mine is aCdkVirtualScrollViewport
element.Then, how can I listen only to my virtual scroll viewport scrolling events?