Search code examples
angularweb-animationsangular-animations

Angular 4 animation state changes


I have an animation applied to two divs to animate them in and out of the void state.

See: https://plnkr.co/edit/uCdBafYG7NZxVVppiTpo?p=preview

Html:

 <div *ngIf="shown" [@flipEnterExitAnimation]="state">
      <div style="border: 1px solid black">Front</div>
    </div>

    <div *ngIf="!shown" [@flipEnterExitAnimation]="state">
      <div style="border: 1px solid black">Back</div>
    </div>

Typescript:

     this.state = this.state === 'backwards' ? null : 'backwards';
      this.shown = !this.shown;

      /*
    setTimeout(() => {
      this.shown = !this.shown;
      },
      1);*/

These animations work, however when the state changes it is not applied to the first animation. I can fix this by delaying the animation for 1ms, but this is ugly and feels a bit hacky.

Is there a neater way to achieve this


Solution

  • A better way is to use change detection (ChangeDetectorRef):

     import { ChangeDetectorRef } from '@angular/core';
    
     // snip
    
    private changeDetectorRef: ChangeDetectorRef;
    
    constructor(changeDetectorRef: ChangeDetectorRef) { 
       this.changeDetectorRef = changeDetectorRef;
    }
    
    beginAnim() {
      this.state = this.state === 'backwards' ? null : 'backwards';
      this.changeDetectorRef.detectChanges();
      this.shown = !this.shown;
    }