raju raju - 3 months ago 33
TypeScript Question

Template variable not updating after scrollEvent in ionic2

I have an Ionic2 app. I am using addScrollListener event to update some variable and want to reflect that change in the Page view.

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


and my Page is

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


scrolledDistance variable is changing in console, but it is not reflected in template.

Answer

The issue in your code is that inside the onPageScroll(..) method, the this keyword is not the component anymore, but the window object (that's why this.scrolledDistance is not the property on your component, but just a new property like window.scrolledDistance).

Please take a look at this plunker to see the solution. There, you can see that in order to avoid that from happening, you can declare the callback of the addScrollListener like this:

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

So in this case it would look like:

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