3

I was wrote this code for showing button after scrolling is more than 500px, but "showButton" didn't get new value.

<ion-content (ionScroll)="onScroll($event)">
    <button *ngIf="showButton">Scroll Top</button>
</ion-content>

my.ts file:

showButton= false;

onScroll($event) {    
  if ($event.scrollTop > 500) {
    console.log(this.showButton);
    this.showButton= true;
  }
}

This console.log shows change of "showButton", but in html it doesn't change.

"showButton" for first time get value "false" but when value change to "true" it can not listen to change, how I can solve this?

M.Hajavi
  • 277
  • 4
  • 17

2 Answers2

5

From the ionic docs, Scroll Events Scroll events happen outside of Angular's Zones. This is for performance reasons. So if you're trying to bind a value to any scroll event, it will need to be wrapped in a zone.run()

<ion-content (ionScroll)="onScroll($event)">
        <button *ngIf="showButton">Scroll Top</button>
</ion-content>

    //add import in .ts file

    import { Component, NgZone } from '@angular/core';


    //in constructor 

    constructor(
        public zone: NgZone,



    showButton= false;

    onScroll($event) {
        this.zone.run(() => {
          if ($event.scrollTop > 500) {
            console.log(this.showButton);
            this.showButton = true;
          }
        })
      }
rashidnk
  • 4,096
  • 2
  • 22
  • 32
0
//Method 1) use boolean variable

    <ion-content (ionScroll)="onScroll($event)">
        <button *ngIf="showButton">Scroll Top</button>
    </ion-content>

    showButton:boolean= false;

    onScroll($event) {    
      if ($event.scrollTop > 500) {
        console.log(this.showButton);
        this.showButton= true;
      }
    }

OR

//Method 2) use number variable

    <ion-content (ionScroll)="onScroll($event)">
        <button *ngIf="showButton==1">Scroll Top</button>
    </ion-content>

    showButton:number= 0;

    onScroll($event) {    
      if ($event.scrollTop > 500) {
        console.log(this.showButton);
        this.showButton= 1;
      }
    }
rashidnk
  • 4,096
  • 2
  • 22
  • 32
  • "showButton" for first time get value "false" but when value change to "true" it can not listen to change, how I can solve this? – M.Hajavi Aug 14 '17 at 05:58