Updated on Kisan Patel
Here is the example of angular directive for sticky header that disappears when you scroll down.
sticky.directive.ts
import { Directive, ElementRef, Inject, Renderer2 } from "@angular/core"; import { fromEvent, Observable } from "rxjs"; import { distinctUntilChanged, map, pairwise, startWith, takeUntil } from "rxjs/operators"; import { DestroyService } from "./destroy.service"; import { WINDOW } from "@ng-web-apis/common"; const THRESHOLD = 200; @Directive({ selector: "[sticky]", providers: [DestroyService] }) export class StickyDirective { constructor( @Inject(DestroyService) destroy$: Observable<void>, @Inject(WINDOW) windowRef: Window, renderer: Renderer2, { nativeElement }: ElementRef<HTMLElement> ) { fromEvent(windowRef, "scroll") .pipe( map(() => windowRef.scrollY), pairwise(), map(([prev, next]) => next < THRESHOLD || prev > next), distinctUntilChanged(), startWith(true), takeUntil(destroy$) ) .subscribe(stuck => { renderer.setAttribute(nativeElement, "data-stuck", String(stuck)); }); } }
app.component.html
<header sticky> I'm sticky & I dissapear when you scroll down pass the threshold & reappear when you scroll up </header>
style.css
[data-stuck] { position: sticky; top: 0; transition: transform 0.3s; } [data-stuck='false'] { transform: translate3d(0, -100%, 0); transition: transform 0.3s 0.5s; }