A super simple, native, angular2 directive for navs (or anything) that become sticky as you scroll down.
To install this directive in your project, run:
$ npm install ng2-sticky-nav --save
and then from your Angular module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Import your library
import { StickyNavModule } from 'ng2-sticky-nav';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
// import module here
StickyNavModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Once you have imported the module, you can use the directive like so:
<nav class="custom-nav-class" ngStickyNav></nav>
The div with ngStickyNav
will now stick to the top once you reach its original position while scrolling down. It will also return to its original position when scrolling up.
Since your nav will be removed from the static DOM when it sticks, I recommend setting up your html/css to account for the lost height like so:
<!-- wrap your header in another div-->
<div class="sticky-nav-wrapper">
<nav class="sticky-nav" ngStickyNav></nav>
</div>
Corresponding css:
:root {
/* setting var for nav height, you can do this however you want */
--sticky-nav-height: 40px;
}
.sticky-nav-wrapper {
/* set min height on wrapper so that the page
doesn't awkwardly snap and lose height */
min-height: var(--sticky-nav-height);
}
.sticky-nav {
height: var(--sticky-nav-height);
/* other styles */
}
Since your nav will be floating on top of other components, be sure that you style your nav so that its z-index is greater than the components it will go over.
In an attempt to make this directive as simple and generic as possible, this is NOT done out of the box.
stickyClass gives you the ability to assign a css class to your navbar when sticky. The styling will automatically be removed when the navbar is not sticky. For example, you can use this to add a box shadow to your nav when sticky like so:
<!-- sample.component.html -->
<div class="sticky-nav-wrapper">
<nav class="sticky-nav" ngStickyNav stickyClass="sticky-box-shadow"></nav>
</div>
/* sample.component.css */
.sticky-nav-wrapper {
min-height: 40px;
}
.sticky-nav {
height: 40px;
}
.sticky-box-shadow {
box-shadow: 0px 0px 10px 5px rgba(0,0,0,0.5);
}
Now your nav will have a slight shadow when in sticky mode. This example can be useful for when your nav is the same color as the components it will be sitting on top of.
MIT © Liam Stokinger