ionic2 中的 scrollEvent 后模板变量未更新

Template variable not updating after scrollEvent in ionic2

我有一个 Ionic2 应用程序。我正在使用 addScrollListener 事件来更新一些变量并希望在页面视图中反映该更改。

scrolledDistance:number = 0;
@ViewChild(Content) contentNew: Content;

ngAfterViewInit() {
   this.contentNew.addScrollListener(this.onPageScroll)
}

onPageScroll(event) {
        setTimeout(() => {
          this.scrolledDistance = event.target.scrollTop;    
          this.shouldShowFab = false;
          console.log("scrolld:::",this.scrolledDistance);
        }, 10)
}

我的主页是

<ion-item>
  {{scrolledDistance}}
</ion-item>

scrolledDistance 变量在控制台中发生变化,但未反映在模板中。

您的代码中的问题是在 onPageScroll(..) 方法内部,this 关键字不再是组件,而是 window 对象(这就是为什么 this.scrolledDistance不是您组件上的 属性,而只是一个新的 属性,例如 window.scrolledDistance)。

请查看 this plunker 以了解解决方案。在那里,您可以看到,为了避免这种情况发生,您可以像这样声明 addScrollListener 的回调:

this.contentNew.addScrollListener((event) => 
  { 
    // here the this keyword refers to the component!! 
  });

所以在这种情况下它看起来像:

  ngAfterViewInit() {
     this.contentNew.addScrollListener((event) => {
       setTimeout(() => {
          this.scrolledDistance = event.target.scrollTop;    
          this.shouldShowFab = false;
          console.log("scrolld:::",this.scrolledDistance);
        }, 10)
     });
  }