Shrinkable mat-toolbar

前端 未结 1 1399
离开以前
离开以前 2020-12-29 14:58

I used the example provided here to set up a responsive navbar

https://theinfogrid.com/tech/developers/angular/responsive-navbar-angular-flex-layout/

<
1条回答
  •  独厮守ぢ
    2020-12-29 15:22

    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.
     
    
    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
    
    
    1. Define the css class for the shrinked layout.
    .shrink-toolbar {
      height: 32px;
    }
    

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

    0 讨论(0)
提交回复
热议问题