Search code examples
angularscrollangular-cdkviewchild

Angular cdkScrollable ViewChild is undefined


I'm trying to listen to scroll event on an element of my template thanks to cdkScrollable.

Typescript:

@ViewChild(CdkScrollable, {static: false})
public scrollable: CdkScrollable;

...

public ngAfterViewInit() {
  this.scrollable.subscribe(this.scrollDetected)
}

Template:

<pre
  cdk-scrollable
  #fareNotes
  [innerHTML]="changeFareNotes">
</pre>

However, this.scrollable is always undefined.

If I try to define the ViewChild as follow, it exists, but only gets the ElementRef type (with only nativeElement property but not the scrollable() method).

 @ViewChild('fareNotes', {static: false})
 public fareNotes: CdkScrollable;

Solution

  • So:

    1. I was missing the ScrollingModule in my module declaration (I only had the CdkScrollable import in my script). I would have expected to get an error for missing this type of thing.
    2. And then, it's either:
      • the generic CdkScrollable ViewChild:
        @ViewChild(CdkScrollable, {static: false}) public scrollable: CdkScrollable;
      • or this syntax to access by selector:
        @ViewChild('fareNotes', {read: CdkScrollable}) public fareNotes:CdkScrollable;

    Credits go to David Fontes and andreivictor for the helpfull comments.