【问题标题】:ionic 2 3, why after scrolling, value of variable doesn't change?ionic 2 3,为什么滚动后变量的值没有改变?
【发布时间】:2017-08-14 14:40:25
【问题描述】:

我写了这段代码,用于在滚动超过 500px 后显示按钮,但“showButton”没有获得新值。

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

my.ts 文件:

showButton= false;

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

这个console.log显示“showButton”的变化,但在html中它没有变化。

“showButton”第一次获取值“false”,但是当值更改为“true”时它不能听变化,我该如何解决这个问题?

【问题讨论】:

  • 感谢@JGFMK,但我没有找到解决方案。
  • 试试这个
  • 我认为 showbutton 不是 boolean 类型,尝试使用数字,showButton:number= 0;并在滚动功能 this.showButton= 1;
  • 如果删除 ngIf,你的按钮会显示吗?

标签: ionic-framework ionic2 ionic3


【解决方案1】:

根据 ionic 文档,滚动事件 滚动事件发生在 Angular 的区域。这是出于性能原因。所以如果你正在尝试 要将值绑定到任何滚动事件,需要将其包装在 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;
          }
        })
      }

【讨论】:

    【解决方案2】:
    //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;
          }
        }
    

    //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;
          }
        }
    

    【讨论】:

    • "showButton" 第一次获取值 "false" 但是当值更改为 "true" 时它不能听变化,我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 2022-12-06
    • 2015-09-30
    • 1970-01-01
    • 2017-07-12
    • 2017-06-23
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多