Job
Job

Reputation: 485

Auto hide Angular Material toolbar (top navigation bar) on scroll down

I currently have an Angular app that uses standard toolbar as the top navigation. picture of top part of my web app

Now I would like the navigation bar to scroll up with the user when they scroll down and reappear when they scroll up.

I've tried using window.pageYOffset but as mentioned here, this value always returns 0.

I've made a Stackblitz with my current setup for my navbar here.

Upvotes: 5

Views: 10102

Answers (2)

Vlad Novikov
Vlad Novikov

Reputation: 447

You can look at this, this is a best example which i found - https://netbasal.com/reactive-sticky-header-in-angular-12dbffb3f1d3

Upvotes: -1

Alex
Alex

Reputation: 1158

The no-JS way

You can do the trick only using CSS. This will hide the navbar progressively as soon as you start scrolling.

.exemple-toolbar {
  position: sticky;
  top: -200px;
  padding-top: 200px;
  height: 250px;
}

The onScroll way

Set a scroll listener on your container div, and add a class to the navbar depending on the scroll direction.

scrollTop = 0;
hideNav = false;

onScroll(event) {
  this.hideNav = this.scrollTop < event.target.scrollTop;
  this.scrollTop = event.target.scrollTop;
}
.container {
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
}

.nav {
  position: fixed;
  height: 50px;
  display: flex;
}

.nav.hide-nav {
  display: none; /* You can play on opacity for nice transitions*/
}
<div class="container" (scroll)="onScroll($event)">

  <div class="nav" [class.hide-nav]="hideNav">
     <!-- Nav -->
  </div>

<!--content-->

</div>

This can work with an HostListener as well, but the parent node of your component has to be scrollable (which is not the case in your example)

Upvotes: 3

Related Questions