Search code examples
angularangular2-templateangular2-directives

class binding and ngClass not working in angular2


My template is :

<div [class.special]="scrollOnTop" ></div>

My class has this public property named "scrollOnTop" which can change depending on the scroll event.

My Class:

export class AppComponent {
constructor() {
    console.log("class initiated with constructor");
    this.scrollOnTop = true;
};

public scrollOnTop: boolean;

onScroll(event){
    console.log("scroll event", event);
    if(event.belowTop){
        this.scrollOnTop = false;
        console.log("scroll on top is - " + this.scrollOnTop)
    }else{
        this.scrollOnTop = true;
        console.log("scroll on top is - " + this.scrollOnTop)
    }
}
};

The div has "special" class when the template is rendered. But if the property "scrollOnTop" changes to false, the "special" class is not removed.

Please help


Solution

  • update

    export class AppComponent { 
      @HostBinding('window:scroll, ['$event'])
      onScroll(event){
        ..
      }
    }
    

    original

    I guess this is caused by the way you set scrollOnTop.

    Ensure the assignment is don't in Angulars zone:

    @Component({
      ...
    })
    export class MyComponent {
      constructor(private zone:NgZone) {}
    
      someMethod() {
    
        ...
        this.zone.run(() => {
          this.scrollOnTop = someValue;
        });
        ...
    
      }
    }