Angular 2动画结束回调函数

4

在 Angular 2 的动画示例中,是否有一种方法可以在动画结束时指定回调函数?

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'))
])
]
4个回答

6

您可以很容易地管理动画,无需依赖Angular动画。 Angular5现在支持大多数回调方法,包括“animationend”回调。 下面是一个基本示例。 一旦触发动画,“anim-slide”,它是包含动画的CSS类附加到DOM上。 这是通过使用“animClass”来完成的,这是一个常规的Angular组件变量。 一旦动画完成,CSS类将从DOM中删除,通过清空“animClass”变量实现

<div (click)="animClass='anim-slide'" >
    <i class="far fa-bell"></i>
 </div>
 <div class="value" [ngClass]="animClass" (animationend)="animClass=''">
     <div>some text that would slide in</div>
 </div>`

参考CSS类

.anim-slide{
    animation-duration: 3s;
    animation-name: slidein;
}
  
@keyframes slidein {
    from {
      margin-left: 100%;
      width: 300%; 
    }
  
    to {
      margin-left: 0%;
      width: 100%;
    }
}


5

Web动画API规定了animationstart和animationend事件,但似乎Angular 2以一种使事件不可访问的方式应用动画。

我尝试使用ViewChild抓取动画元素并应用事件监听器(直接和Renderer两种方式),但回调从未被调用。

可以在实际启动动画状态变化时指定超时,这会在与过渡长度相等的时间后调用回调函数。

startAnimation() {
  this.hero.state = 'active';
  setTimeout(() => {
    //Do something after the animation.
  }, 100);
}

这是有点麻烦的,因为如果你想改变动画时间,你需要改变转换和超时延迟,但它足够好用。今天我尝试了一些东西,在翻译动画结束时,我立刻切换到静态动画状态(使用0毫秒的转换),同时使用Renderer应用静态翻译。它运行流畅,没有任何跳跃或中断。


3
现在该特性已被支持,具体信息请参见这里:https://angular.io/docs/ts/latest/guide/animations.html#!#animation-callbacks 这个功能似乎是自2.0.0-rc.6 (2016-08-31)版本开始实现的。
例如: 如果您有一个名为“flyInOut”的触发器,您只需将其添加到模板代码中即可:
<div (@flyInOut.start)="animationStarted($event)"
     (@flyInOut.done)="animationDone($event)"></div>

事件(来自核心的AnimationTransitionEvent)提供有关触发状态的有用信息(例如fromState和toState)。

不幸的是,您无法接收有关动画进度的事件(例如@yourTrigger.animate)。


虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。-【来自审查】 - arghtype
1
@arghtype 好的,我更新了我的答案。 - Davide Perozzi

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接