Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent angular animation when switching route

Tags:

angular

I have an array of object that I want to animate on delete :

<div [@arrayAnim]="motives.length">
    <div class="motive" *ngFor="let motive of motives"><div>
    <div class="motive-name">{{motive.name}}</div>
    ...

    <mat-icon class="delete-icon" (click)="deleteMotive(motive)">delete</mat-icon>
</div>

In my component animations I built an array animation trigger as follow :

@Component({
  selector: 'app-motives',
  templateUrl: './motives.component.html',
  styleUrls: ['./motives.component.scss'],
  animations: [
    trigger('arrayAnim', [
      transition('* => *', [
        query(':leave', stagger('300ms', [
          animate('500ms ease-out', keyframes([
            style({opacity: 1, transform: 'scale(1.1)', offset:0}),
            style({opacity: .5, transform: 'scale(.5)', offset: .3}),
            style({opacity: 0, transform: 'scale(0)', offset:1})
          ]) )
        ]), {optional: true})
      ])
    ])
  ]
})

When siwtching route, the transition is triggered even though I'm not deleting any element of the array. I don't understand this behavior. Why is the animation triggered on route change ?

enter image description here

I have created a minimal example on stackblitz :

https://stackblitz.com/edit/angular-ivy-wdyzlh?file=src/app/prices/prices.component.ts

Switching from prices to products to prices routes will trigger the unexpected behavior. Deleting a price will work as expected.

Update

As suggested in the comment I can wrap the arrayAnim div within another one that would disable animations based on a component variable.

<div [@.disabled]="noAnimation">
    <div [@arrayAnim]="motives.length" (@arrayAnim.done)="onAnimationDone()">
        <div class="motive" *ngFor="let motive of motives"><div>
        <div class="motive-name">{{motive.name}}</div>
        ...

        <mat-icon class="delete-icon" (click)="deleteMotive(motive)">delete</mat-icon>
    </div>
</div>

In my component I'd have a noAnimation property that would be switched to true once the deletion is done. The no animation property would be set to false when triggering deleteMotive() method

like image 321
Ado Ren Avatar asked Sep 18 '25 02:09

Ado Ren


1 Answers

Try this:

<div [@.disabled]="noAnimation">
  <div [@arrayAnim]="priceArray.length">
    <div *ngFor="let p of priceArray" class="price" (click)="deletePrice(p)">
      Regular: {{p.regular}}
      Discounted: {{p.discounted}}
    </div>
  </div>
</div>
<p>Click on a price to delete it</p>

Component.ts:

  noAnimation = true;

  deletePrice(p) {
    this.noAnimation = false;
    this.priceArray = this.priceArray.filter(price => price != p);

    //After animiation was executed - disable it again

    setTimeout(()=> {
      this.noAnimation = true;
    }, 500);
  }
like image 149
angularQuestions Avatar answered Sep 19 '25 17:09

angularQuestions