Angular 6滚动事件

3

我在我的组件中使用了Angular的cdkScrollable实现了滚动事件。

我的代码如下:

export class HomeComponent {
    public hide = true;

    constructor(public scrollDispatcher: ScrollDispatcher) {
        this.scrollDispatcher.scrolled().subscribe((cdk: CdkScrollable) => {
            offset = cdk.getElementRef().nativeElement.scrollTop || 0;

            if (offset > 50) {
                this.hide = false;
            } else {
                this.hide = true;
            }
        });
    }
}

我的home.component.html代码如下:
<p>{{hide}}</p>

问题在于即使滚动超过 64,hide 的值也不会改变,但在 console.log 中它却改变了。
我做错了什么?

你找到解决办法了吗?我也遇到了同样的问题,但是区域建议并没有起作用。 - Lereveme
3个回答

1

ScrollDispatcher不在Angular的更新周期中运行。您需要在NgZone中运行更改。

this.zone.run(_ => {
  this.hide= false;
});

0

我使用了来自@angular/coreChangeDetectorRef手动触发变更检测。

export class HomeComponent {
    public hide = true;

    constructor(
        public scrollDispatcher: ScrollDispatcher,
        private cdr: ChangeDetectorRef
    ) {
        this.scrollDispatcher.scrolled().subscribe((cdk: CdkScrollable) => {
            offset = cdk.getElementRef().nativeElement.scrollTop || 0;

            if (offset > 50) {
                this.hide = false;
                this.cdr.detectChanges();
            } else {
                this.hide = true;
                this.cdr.detectChanges();
            }
        });
    }
}

在一个严格类型的应用程序中,我必须显式地将cdk转换为 this.scrollY = (cdk as CdkScrollable).getElementRef().nativeElement.scrollTop || 0; - Stephane

0
尝试这样做: 1. 导入 NgZone:
import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';

在构造函数中创建一个私有访问NgZone,并使用NgZone更新您的值: ``` constructor(private scroll: ScrollDispatcher, private zone: NgZone) { this.scrollDispatcher.scrolled().subscribe((cdk: CdkScrollable) => { this.zone.run(() => { // Your update here! }); }) } ``` 有关更多信息,请阅读此文章:https://sumodh.com/2018/03/31/how-to-force-update-a-variable-in-angular-4-angular-5/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接