Search code examples
angularcss-animationsangular-animations

Animate cards to enter and leave left/right in Angular 2+


I have a component where the user should be able to sift through a list of items with left and right arrowkey, and to really make it clear which way the user is going i want to use animations. I've managed to add animation for the first interaction the user do but beyond that the animation isnt applying, i'll provide a stackblitz with the issue below:

https://stackblitz.com/edit/angular-ivy-7h2sdp?file=src/app/app.component.html

As seen in the example if you input rightkey once the animation is applied and if you go right-key and back with left-key it's also applied correctly but if you do it multiple times in the same direction it stops getting applied but i assign the direction variable that the trigger is checking so in my mind it should apply each time you hit the key? I'm guessing there's something i'm not understanding when applying the animation.

Any help would be greatly appreciated!


Solution

  • Trigger would fire when it sees some changes in the bounded variable.

    Trigger:- Creates a named animation trigger, containing a list of state() and transition() entries to be evaluated when the expression bound to the trigger changes.

    In given example this.direction is not changing (ex. if user press right/left key multiple times), so animation not triggering.

    Resetting this.direction variable and making call to changedetector should work.

     keyEvent(event: KeyboardEvent) {
        this.direction = ""; //resetting varibale
        this.cd.detectChanges(); //run change detection cycle
        if (event.key === "ArrowRight") {
          this.moveRight();
          this.currentItem = this.items[this.index];
          this.direction = "fromRight";
        }
    
        if (event.key === "ArrowLeft") {
          this.moveLeft();
          this.currentItem = this.items[this.index];
          this.direction = "fromLeft";
        }
        this.count++;
      }