The Angular Material CDK provides a Directive
CdkScrollable
, which allows you to listen to ScrollEvent
s of a specific container.
I am now trying to access the CdkScrollable
of the MatSidenavContent
, which is added by default.
However my @ViewChild(CdkScrollable) and @ContentChild(CdkScrollable) are always undefined.
My Component
looks something like this:
<mat-sidenav-container>
<mat-sidenav>Sidenav content</mat-sidenav>
<div>Main content</div>
</mat-sidenav-container>
The resulting DOM looks something like this:
<mat-sidenav-container>
<div class="mat-drawer-backdrop"></div>
<div tabindex="-1" class="cdk-visually-hidden cdk-focus-trap-anchor"></div>
<mat-sidenav>Sidenav content</mat-sidenav>
<mat-sidenav-content cdkScrollable>
<div>Main content</div>
</mat-sidenav-content>
</mat-sidenav-container>
The mat-sidenav-content
Component
, which is generated automatically, uses a CdkScrollable
-Directive, which I need to access.
My question is now:
Is it possible to access that Directive
and if so, how?
I opened an Issue on @angular/material some time ago and they now expose the
CdkScrollable
-Instance.To use it, you need to access the
MatSidenavContainer
using@ViewChild(MatSidenavContainer
. This instance has a public memberscrollable
, which is theCdkScrollable
instance.An example can be found here
Edit: As the example is not very complete and a few people are having difficulties implementing it, I'll write my own example here:
HTML:
TypeScript:
Important:
<mat-sidenav-content>
. This tag is generated automatically and it has thecdkScrollable
directive attached to it. If you use<mat-sidenav-content>
in your own template, thescrollable
will be undefined.AfterViewInit
instead ofOnInit
. As much as I know,@ViewChild
is resolved inAfterViewInit
,OnInit
is probably too early.a) inject ScrollDispatcher from @angular/cdk/overlay and subscribe to scrolling:
c) do something when scrolling, e.g. check the offset
Documentation: https://material.angular.io/cdk/scrolling/api