Search code examples
javascriptangularng-class

Angular 2 add class conditionally


My target is to set or remove class depending on component boolean with Angular 2. For example: isRed = true > add class "red", if isRed = false > remove class "red". How is that possible? Code tried:

isRed: boolean;

constructor() {
    $(document).scroll(function(){
        var scrollTop = $(this).scrollTop();
        if(window.location.hash) {

        } else{
            this.isRed = true;
        }
        if(scrollTop > 50) {
            this.isRed = true;
        }
        else  {
            this.isRed = false;
        }
    });
}

and html:

[ngClass]="{red: isRed}"

Solution

  • The most concise way is IMHO

    [class.red]="isRed"
    

    update

    The cause of your problem is function in

     $(document).scroll(function(){
    

    it should use arrow function

     $(document).scroll(() => {
    

    otherwise this within the callback won't point to the current class, but instead to the caller.

    I'd suggest you try to avoid jQuery with Angular2. Use instead

    class MyComponent {
    
      constructor(private elRef:ElementRef) {}
    
      isRed:boolean;
    
      @HostListener('document:scroll', ['$event'])
      onScroll(event:any) {
        var scrollTop = this.elRef.nativeElement.scrollTop;
        // or
        $(this.elRef.nativeElement).scrollTop();
    
        if(window.location.hash) {
    
        } else{
            this.isRed = true;
        }
        if(scrollTop > 50) {
            this.isRed = true;
        }
        else  {
            this.isRed = false;
        }
      }
    }