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 that scrolled()
is triggered on scrolling on the whole component, then I figure out that it is bind to the component instead of just to CdkVirtualScrollViewport
.
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 of scrollDispatcher
... but I should pass a CdkScrollable
to it, instead mine is a CdkVirtualScrollViewport
element.
Then, how can I listen only to my virtual scroll viewport scrolling events?
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...