I used the example provided here to set up a responsive navbar
https://theinfogrid.com/tech/developers/angular/responsive-navbar-angular-flex-layout/
<
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.
CdkScrollDispatcher
service to react to scroll eventsScrollDispatchModule
in your module.import {ScrollDispatchModule} from '@angular/cdk/scrolling';
cdkScrollable
, here it is mat-sidenav-content
.
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.
.shrink-toolbar {
height: 32px;
}
Find more information about the scroll service in the official docs.