How can I implement a dynamic class in my view?

I am using Ionic 2 which sits on top of Angular 2. I would like to add a class to my element ion-header

. This means that my title has a transparent background initially, but a solid background for scrolling.

I set a variable in my Typescript file and update this variable when the user scrolls down.

I need to set a class based on a variable in my Typescript variable. I have done this elsewhere in my application with help [ngClass]="{showBack: navBack}"

, but it doesn't seem to work on this page.

Typescript:

import { Component, ViewChild } from '@angular/core';
import { Content } from 'ionic-angular';

@Component({
  selector: 'page-class',
  templateUrl: 'class.html'
})
export class ClassPage {
  @ViewChild(Content)
  content: Content;
  navBack: boolean = false;

  constructor(...){}

  ngAfterViewInit() {
    this.content.ionScroll.subscribe((event) => {
      if(event.scrollTop == 0) {
        this.navBack = false;
      } else {
        this.navBack = true;
      }
    });
  }

}

      

HTML:

<ion-header [ngClass]="{showBack: navBack}">
  <ion-navbar>
    <ion-title>Test</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <p style="height: 300px">Long page of content here.</p>
  <p style="height: 300px">Long page of content here.</p>
  <p style="height: 300px">Long page of content here.</p>
</ion-content>

      

I expect to see a showBack

CSS class on mine ion-header

that appears in the scroll, however it never appears, no matter the value event.scrollTop

.

I have done some debugging with console.log

in the function ngAfterViewInit

and I can confirm that the variable is changed correctly, but the class is not updated.

+3


source to share


2 answers


For something to trigger change detection, it must be done in the Angular s zone.



import { Component, ViewChild, NgZone } from '@angular/core';
import { Content } from 'ionic-angular';

@Component({
  selector: 'page-class',
  templateUrl: 'class.html'
})
export class ClassPage {
  @ViewChild(Content)
  content: Content;
  navBack: boolean = false;

  constructor(private ngZone: NgZone){}

  ngAfterViewInit() {
    this.content.ionScroll.subscribe((event) => {
      this.ngZone.run(() => {
          if(event.scrollTop == 0) {
            this.navBack = false;
          } else {
            this.navBack = true;
          }
    });
   });
}

}

      

+1


source


Must not be:

[ngClass]="{'showBack': navBack}"

      



(you are missing single quotes)

+1


source







All Articles