4

If I have started an animation with Angular, how can I stop it before it is finished?

I could need to stop an animation for example if I have an animation when a user clicks on something. And if the user clicks again before the animation is finished, I would like to stop it and restart it.

For example, the Angular docs have this animation:

animations: [
    trigger('heroState', [
      state('inactive', style({
        backgroundColor: '#eee',
        transform: 'scale(1)'
      })),
      state('active',   style({
        backgroundColor: '#cfd8dc',
        transform: 'scale(1.1)'
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ])
  ]

So, if the animation is triggered, how can I stop it before it is completed?

EricC
  • 5,720
  • 13
  • 52
  • 71

1 Answers1

1

I am not sure that's exactly what you need but I think it should be pretty close to it.

Using animation states, you could have one state dedicated to reset the animation.

Here is a StackBlitz example of a progress bar I made to explain myself better : https://stackblitz.com/edit/angular-stop-anim

animations.ts

import { trigger, style, animate, transition, state } from '@angular/animations';

export const load = [
  trigger('load', [
    state('left', style({ 'width': '0px' })),
    state('right', style({ 'width': '500px' })),
    state('reset', style({ 'width': '0px' })),
    transition('left <=> right', [
      animate(5000)
    ]),
     transition('reset => *', [
      animate(5000)
    ]),
  ])
];

component.html

<button (click)="runAnimation()">Run animation</button>
<button (click)="stopAnimation()">Stop animation</button>

<div class="bar bar-div"></div>
<div [@load]="state" class="loading-bar bar-div"></div>

component.ts

import { Component } from '@angular/core';
import { load } from './animations';

@Component({
  ...
  animations: [load]
})
export class AppComponent {
  ...
  state = 'left';

  runAnimation() {
    this.state = 'left';
    this.state = 'right';
  }

  stopAnimation() {
    this.state = 'reset';
  }
}

I set the transition between the states wanted (here left-right), but none to go back to the reset state (so it stops instantly).

And finally, when you want to stop the animation, you change the current state to 'reset'.

br.julien
  • 3,420
  • 2
  • 23
  • 44