如何在 ionic 4 的滚动条上隐藏 header?

How to hide header on scroll in ionic 4?

我想知道如何通过向下滚动页面在 Ionic 4 中隐藏 header 并在向上滚动时 re-show 它。

我找到了很多关于如何做到这一点的解决方案,但结果都无法正常工作或 out-of-date。

所以我收集了我能找到的所有信息来提供这个答案。

多亏了 this video 我让它开始工作了。

首先调用ionic g directive directives/hide-header。您当然可以将 directive/hide-header 替换为您自己的路径和名称。

hide-header.directive.ts

import { Directive, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { DomController } from '@ionic/angular';

@Directive({
    selector: '[appHideHeader]'
})
export class HideHeaderDirective implements OnInit {

    @Input('header') header: any;

    private lastY = 0;

    constructor(
        private renderer: Renderer2,
        private domCtrl: DomController
    ) { }

    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.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;
    }

}

之后,在您的模板中:

<ion-header #header>
    <ion-toolbar><ion-title>Test</ion-title></ion-toolbar>
</ion-header>
<ion-content scrollEvents="true" appHideHeader [header]="header">
</ion-content>

注意 scrollEventsappHideHeader[header] 属性!最后一个将 header 元素作为参数,在本例中为 #header.


大部分代码与视频中显示的相同。我将 host-属性 从 @Directive 更改为 up-to-date HostListener.

如果要在多个指令中使用该指令,则需要创建一个SharedModule

为此,使用 ng g module shared 创建模块。之后,将 HideHeaderDirective 添加到 declarationsexports 数组。

shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HideHeaderDirective } from './directives/hide-header.directive';


@NgModule({
    declarations: [HideHeaderDirective],
    exports: [HideHeaderDirective],
    imports: [
        CommonModule
    ]
})
export class SharedModule {}

现在将共享模块添加到您要在其中使用该指令的所有模块。

Note: You cannot import the directive in app.module.ts and use it in a submodule! You have to import the shared module in every direct module you want to use the directive in.

我当前的 nodenpmionic 版本:

为此,您可以将 ion-header 放在 ion-content 之前。这是对此的简单答案。