Last active
September 30, 2023 20:35
-
-
Save klemensz/2a91bbe764bf4b0046b47840b6bef429 to your computer and use it in GitHub Desktop.
Hide header on scroll in Ionic 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, HostListener, Input, OnInit, Renderer2 } from '@angular/core'; | |
import { DomController } from '@ionic/angular'; | |
/** | |
* Moves away the header when scrolling down. | |
*/ | |
@Directive({ | |
selector: '[appHideHeader]', | |
}) | |
export class HideHeaderDirective implements OnInit { | |
@Input('header') header: any; | |
/** | |
* Minimum scroll offset from top in pixels until the animation kicks in. | |
*/ | |
@Input('scrollThreshold') scrollThreshold: number; | |
private lastY = 0; | |
constructor(private renderer: Renderer2, private domCtrl: DomController) { | |
// Doing nothing. | |
} | |
ngOnInit(): void { | |
this.header = this.header.el; | |
this.domCtrl.write(() => { | |
this.renderer.setStyle(this.header, 'transition', 'margin-top 700ms'); | |
}); | |
} | |
@HostListener('ionScroll', ['$event']) onContentScroll($event: any) { | |
if ( | |
$event.detail.scrollTop > (this.scrollThreshold || 0) && | |
$event.detail.scrollTop > this.lastY | |
) { | |
this.domCtrl.write(() => { | |
this.renderer.setStyle(this.header, 'margin-top', `-${this.header.clientHeight}px`); | |
}); | |
} else { | |
this.domCtrl.write(() => { | |
this.renderer.setStyle(this.header, 'margin-top', '0'); | |
}); | |
} | |
this.lastY = $event.detail.scrollTop; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more information see How to hide header on scroll in ionic 4? (It refers to this answer: https://stackoverflow.com/a/56996295/769726)