动画回调即使状态不变也可以立即运行

时间:2020-05-05 21:29:48

标签: angular angular-animations

我正在按角度创建动画,我需要知道动画何时开始,因此我定义了一个回调。关键是,即使在不更改状态的情况下,加载组件时也会触发回调。

模板

<button (click)="click()">click</button>
<div class="myclass" [@throwBall]="state" (@throwBall.start)="animStart($event)" >  
</div>  

组件:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger('throwBall', [
      state('steady', style({ })),
      state('throw', style({ top: '300px' })),
      transition('steady => throw', [animate('2s')])
    ]),
    trigger('blockInitialRenderAnimation', [
        transition(':enter', [])
    ])
  ]
})
export class AppComponent  {
  state = 'steady';

  click() {
    this.state = 'throw';
  }
  animStart(event: any) {
    if (event.fromState !== 'void') {
      console.log('anim start callback');
    }
  }
}

这是一个演示: https://stackblitz.com/edit/angular-9szgic

为什么在加载组件时控制台中会显示“动画启动回调”?

1 个答案:

答案 0 :(得分:1)

动画的初始状态是一个称为void的“无状态”状态-这是使用动画时的默认状态。 将state变量初始化为steady后,一个不存在的动画将从void-> steady开始。

为了达到目标,您应该使用AnimationEvent的属性fromStatetoState

import { AnimationEvent, } from '@angular/animations';

public animStart(event: AnimationEvent): void {
   if(event.fromState === 'steady') {
      // ...
   }
}

请尝试在您的AnimationEvent方法中登录animStart,以便更好地理解interface

public animStart(event: AnimationEvent): void {
   console.log(event);
}