Whitewolf3131
Whitewolf3131

Reputation: 79

ngClass not working when changing condition in jQuery function

I'm building a web application in Angular and I've been trying to dynamically change classes using the ngClass directive. However when updating the condition of the directive it doesn't always work.

I've tried updating the condition in a jQuery callback function when I'm scrolling, yet it does not work. However, when I change the condition's value via a function it works! I will give you the code below so you can understand what I'm talking about.

navbar.component.ts

export class NavbarComponent implements OnInit {
  stickyNavbar = false;
  constructor() { }

  ngOnInit() {
    $(document).ready(() => {
      let scrolled = false;
      $(document).scroll(()=>{
        this.stickyNavbar = true;
        console.log(this.stickyNavbar);
      })
    })
  }
  public test() {
    this.stickyNavbar = true;
  }
}

navbar.component.html

<li class="nav-item active">
        <a class="nav-link" [ngClass]="{'dark': stickyNavbar, 'light': !stickyNavbar}" href="#">Home</a>
      </li>
<li class="nav-item">
        <button class="btn nav-link" [ngClass]="{'dark': stickyNavbar, 'light': !stickyNavbar}" (click)="test()">Test</button>
      </li>

Normally, when I change stickyNavbar to true, <li> should get the dark class. This does not happen when scrolling the page, but if I press the button which calls the test() function it works and changes classes. If I call the test() function inside the jQuery scroll() function, it does not work. By the way, I'm using Angular 8.

EDIT: *ngIf doesn't work either.

Upvotes: 0

Views: 269

Answers (1)

Eliseo
Eliseo

Reputation: 57981

if you use jQuery (personally I don't like use jQuery and Angular, JQuery change the DOM, but you loose the view-model relation,futhermore Angular has enougth mechanics to avoid the use of jQuery), you need use ngZone. Angular don't know anything outside Angular

constructor(private _ngZone: NgZone){}
ngOnInit() {
    $(document).ready(() => {
      let scrolled = false;
      $(document).scroll(()=>{
        this._ngZone.run(() => { 
        this.stickyNavbar = true; 
         });
      })
    })
  }

But, in this case, you can use a simple HostListener

  @HostListener('document:scroll',['$event'])
  onScroll(event:any)
  {
        this.stickyNavbar = true;
  }

See a demo in stackblitz

Upvotes: 1

Related Questions