简体   繁体   中英

Remove and add class dynamically triggering change detection in between (Angular 2+)

In short, I am trying to trigger a change detection loop between renderer.removeStyle and renderer.addStyle . The style I am adding is an css animation. When it's removed and added in the same change detection loop Angular won't detect that something changed (for the same animation name).

More Details

Let's say I have a button event (click)="addAnimation('animation1')" that should add existing animation and add the new animation named animation1, animation2 ... . Of course the following code won't work:

  addAnimation(): void {
    this.renderer.removeStyle(this.animate.nativeElement, 'animation');
    // setTimeout(() => {
      this.renderer.setStyle(this.animate.nativeElement, 'animation', 'moveInLeft 1s')
    // }, 0);
  }

since removing and adding a style under angular nose won't trigger any change.

One possible solution is adding a timeout (like the commented code above, but it has side effects that I am not interested in, and also the code is a little wired.

I was hoping to solve it by adding something like this.appRef.tick(); in between to force angular create another change detection loop.

That doesn't work, what am I missing? any suggestions how to do that correctly? Thanks!

Try following way.

isClick=false;
onClick(){
    isClick=true;
}

<div [ngClass]="{'yourCSSClass': isClick}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM