Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 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 class="footer">
{{footer}}
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...
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.