Eliya Cohen
Eliya Cohen

Reputation: 11468

Angular 4 - property value isn't being updated in the view

I have a HomePage page with a property shouldNavBeTransparent: boolean = true which indicates if the navbar of the page should have a class="transparent or not.

After the window has reached 90% of its height, I set the property shouldNavBeTransparent to true.

My problem is that the property isn't being changed in the view. In the view, it's always false, while in the component, it's being changed.

This is my home.ts file:

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

The console.log in scrollHandler outputs true and false, which indicates it is changing: indicating the property is being changed

The part where I check the property in my view is (home.html):

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

The part where I trigger the scroll event:

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

Even when I write {{ shouldNavBeTransparent }} all I get is true.


I'm using Ionic v3.19.1

Upvotes: 3

Views: 70

Answers (2)

Melchia
Melchia

Reputation: 24244

After doing some research I found that you need to use ngZone.

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

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

Upvotes: 1

Stephan Strate
Stephan Strate

Reputation: 1421

You can use ngClass to assign classes conditionally:

<div [ngClass]="{'yourclass':yourcondition}">

For your specific problem:

<ion-header [ngClass]="{'transparent':shouldNavBeTransparent}">

Edit:

import { ChangeDetectorRef } from '@angular/core';

constructor (private ref: ChangeDetectorRef) {}

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

this.ref.detectChanges(); should manually update your variable.

Upvotes: 1

Related Questions