Angular-Material Sidenav cdkScrollable

后端 未结 2 1117
面向向阳花
面向向阳花 2020-12-30 05:23

The Angular Material CDK provides a Directive CdkScrollable, which allows you to listen to ScrollEvents of a specific container.

2条回答
  •  情歌与酒
    2020-12-30 06:11

    1. Add to your app module imports: ScrollDispatchModule.
    2. Add cdkScrollable to your mat-sidenav-content:

    1. In your root component:

    a) inject ScrollDispatcher from @angular/cdk/overlay and subscribe to scrolling:

    constructor(public scroll: ScrollDispatcher) {
    
        this.scrollingSubscription = this.scroll
              .scrolled()
              .subscribe((data: CdkScrollable) => {
                this.onWindowScroll(data);
              });
    }
    

    c) do something when scrolling, e.g. check the offset

    private onWindowScroll(data: CdkScrollable) {
        const scrollTop = data.getElementRef().nativeElement.scrollTop || 0;
        if (this.lastOffset > scrollTop) {
          // console.log('Show toolbar');
        } else if (scrollTop < 10) {
          // console.log('Show toolbar');
        } else if (scrollTop > 100) {
          // console.log('Hide toolbar');
        }
    
        this.lastOffset = scrollTop;
      }
    

    Documentation: https://material.angular.io/cdk/scrolling/api

    Update Angular 9 :

    Use import {ScrollingModule} from '@angular/cdk/scrolling', ScrollDispatchModule is deprecated

提交回复
热议问题