如何在动画结束前停止动画?

时间:2017-11-29 07:41:28

标签: angular angular-animations

如果我已经使用Angular启动了动画,如何在完成之前停止它?

如果我在用户点击某些内容时有动画,我可能需要停止动画。如果用户在动画结束前再次点击,我想停止并重新启动它。

例如,Angular文档有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'))
    ])
  ]

因此,如果动画被触发,我怎么能在它完成之前停止它?

1 个答案:

答案 0 :(得分:0)

我不确定你到底需要什么,但我认为它应该非常接近它。

使用动画状态,您可以拥有一个专门用于重置动画的状态。

这是我更好地解释自己的进度条的StackBlitz示例: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';
  }
}

我设置了所需状态之间的转换(此处为左右),但没有设置为返回 reset 状态(因此它会立即停止)。

最后,当你想停止动画时,你将当前状态改为&#39; reset&#39;。

相关问题