【问题标题】:Angular 6 scrolling eventAngular 6 滚动事件
【发布时间】:2018-10-05 15:02:00
【问题描述】:

我使用 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>

问题是 hide 的值即使滚动超过 64 也不会改变,但在 console.log 中它会改变。

我做错了什么?

【问题讨论】:

  • 您找到解决方案了吗?我遇到了同样的问题,并且区域建议不起作用。

标签: angular angular6 angular-cdk


【解决方案1】:

ScrollDispatcher 未在角度更新周期中运行。您需要在 NgZone 中运行您的更改

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

【讨论】:

    【解决方案2】:

    试试这个: 1. 导入 NgZone:

    import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
    
    1. 在构造函数中创建对 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/

    【讨论】:

      【解决方案3】:

      我已使用@angular/core 中的ChangeDetectorRef 手动触发更改检测。

      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();
                  }
              });
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-25
        • 1970-01-01
        • 2020-10-24
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        相关资源
        最近更新 更多