Shrinkable mat-toolbar

拟墨画扇 提交于 2019-12-03 03:27:52

Update Nov 2018

The ScrollDispatchModule was deprecated with Angular CDK v7. Use the ScrollingModule instead.


I've created a Stackblitz with a toolbar that shrinks when scrolling down.

Main Steps

Use the CdkScrollDispatcher service to react to scroll events

  1. Import the ScrollDispatchModule in your module.
import {ScrollDispatchModule} from '@angular/cdk/scrolling';
  1. Mark the containers of which the scroll events are relevant with the directive cdkScrollable, here it is mat-sidenav-content.
 <mat-sidenav-content fxFlexFill cdkScrollable>
  1. React to scroll events in the ngOnInit of your component, get the scrollTop position and set a flag if it is larger than a certain threshold:
private readonly SHRINK_TOP_SCROLL_POSITION = 50;
shrinkToolbar = false;

constructor(private scrollDispatcher: ScrollDispatcher,
            private ngZone: NgZone) { }

ngOnInit() {
  this.scrollDispatcher.scrolled()
    .pipe(
      map((event: CdkScrollable) => event.getElementRef().nativeElement.scrollTop)
    )
    .subscribe(scrollTop => this.ngZone.run(() => this.shrinkToolbar = scrollTop > this.SHRINK_TOP_SCROLL_POSITION ? true : false));
}

You need to run this with ngZone because scrolled() events of the ScrollDispatcher are run outside of Angular by default. Without it, the ChangeDetection won't run and your templates won't be updated.

Change the toolbar layout on scroll

  1. Add a shrink css class, when the container is scrolled down
<mat-toolbar color="primary" [ngClass]="{'shrink-toolbar': shrinkToolbar}">
  1. Define the css class for the shrinked layout.
.shrink-toolbar {
  height: 32px;
}

Find more information about the scroll service in the official docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!