I currently have an Angular app that uses standard toolbar as the top navigation.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With