Angular 4 - 属性值未在 View 中更新

标签 angular typescript ionic-framework ionic2 ionic3

我有一个 HomePage 页面,其属性 shouldNavBeTransparent: boolean = true 指示页面的 navbar 是否应该有一个 class="是否透明

在窗口达到其高度的 90% 后,我将属性 shouldNavBeTransparent 设置为 true。

我的问题是 View 中的属性未更改。在 View 中,它始终为 false,而在组件中,它正在发生变化。

这是我的home.ts 文件:

import {Component} from '@angular/core';
import {IonicPage} from 'ionic-angular';

@IonicPage({segment: "/"})
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {

  services: Array<{ icon: string, title: string, subhead: string, content: string }>;

  shouldNavBeTransparent: boolean = true;

  scrollHandler($event) {
    this.shouldNavBeTransparent = ($event.scrollWidth * 0.9) < $event.scrollTop;
    console.log(this.shouldNavBeTransparent);
  }
}

scrollHandler 中的console.log 输出true 和false,这表明它正在发生变化: indicating the property is being changed

我在 View 中检查属性的部分是 (home.html):

<ion-header [class.transparent]="shouldNavBeTransparent">

我触发滚动事件的部分:

<ion-content (ionScroll)="scrollHandler($event)">

即使我写 {{ shouldNavBeTransparent }} 我得到的都是真的。


我正在使用 Ionic v3.19.1

最佳答案

经过一些研究,我发现您需要使用 ngZone

滚动事件发生在 Angular 的区域之外。这是出于性能原因。因此,如果您尝试将值绑定(bind)到任何滚动事件,则需要将其包装在 zone.run()

import { Component, NgZone } from '@angular/core';
 constructor( public zone: NgZone){}
scrollHandler($event) {
   this.zone.run(()=>{
     // the update needs to happen in zone
    this.shouldNavBeTransparent = ($event.scrollWidth * 0.9) < $event.scrollTop;
    console.log(this.shouldNavBeTransparent);
   })

关于Angular 4 - 属性值未在 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211179/

相关文章:

css - 如何更改 Ionic 4 中子弹 slider 的 Prop ?

angular - 在哪里以及如何导入 MAT_LABEL_GLOBAL_OPTIONS?

angular - 当组件属性在回调中更改时绑定(bind)不更新

angular - rxjs - 是否有一个always运算符?你总是怎么做某事?

angular - 订阅 RxJS Observable 两次。两次获得响应值

angular - 我需要监听表单中是否有任何更改,如果有更改则启用/禁用“保存”按钮 | Angular

angular - 类未定义的 typescript 方法

android - 蓝牙串口 - Ionic 2

ionic-framework - 滑动时不会触发 slideChangeStart 事件

javascript - ionic 不显示图像