【问题标题】:Angular Animations: How to set transition timing dynamically?Angular Animations:如何动态设置过渡时间?
【发布时间】:2021-06-30 18:20:09
【问题描述】:

我目前正在一个应用程序中实现动画,我面临的问题是动画转换的时间存储在一个 json 配置文件中(我无法更改它)。有一个服务可以提供所需的值,但由于在 @Component 块中声明了 Angular Animations,我无法访问该服务。

transition('start => end', [animate(ConfigService.config.delay.firstDelay)])

正如预期的那样,这会导致未定义的错误。我看到可以使用AnimationBuilder 构建动画,但这样做似乎只能提供提供简单动画的机会,而无需特定的回调和多个状态转换。

以动态方式实现过渡时间的最佳方法是什么?

【问题讨论】:

标签: angular angular-animations


【解决方案1】:

您可以使用“手动动画”。典型动画和手动动画的“翻译”并不难

在您定义的组件中

import {style,animate,AnimationBuilder,AnimationFactory,AnimationPlayer} from "@angular/animations";

 private player: AnimationPlayer;
 constructor(private builder: AnimationBuilder) {}

并创建一个“动画”元素的函数,例如

/*I want "recreate" the animation
 transition(':enter', [
    style({ opacity: 0 }),
    animate('100ms', style({ opacity: 1 })),
  ]),
  transition(':leave', [
    animate('100ms', style({ opacity: 0 }))
  ])
*/
animate(element: any, state:string) {
    const myAnimation = state=='enter'?
       this.builder.build([
          style({ opacity: 0 }),
          animate(this.timing, style({ opacity: 1 }))
       ]):
       this.builder.build([
        animate(this.timing, style({ opacity: 0 }))
     ])
     ;
    this.player = myAnimation.create(element);
    //you can control when the animation is finish
    this.player.onDone(()=>{
        this.toogle=!this.toogle;
    })
    this.player.play();
  }

所以你可以拥有,例如

<div #div style="background-color:red;width:5rem;height:5rem"></div>
<button (click)="animate(div,toogle?'enter':'leave');">click</button>

或使用 ViewChild 获取元素并制作动画或调用 ngOnInit 或...

【讨论】:

  • 您知道如何将@trigger.done 回调添加到使用AnimationBuilder 创建的动画中吗?这对于在前一个完成后显示动画至关重要。 AnimationPlayer.play() 不接受回调参数。 Animation.Stop() 函数似乎触发了 onDone 回调,但 API 没有提及您如何设置结果调用的函数。
  • 我只是更新了答案,是在调用player.play()之前“控制”this.player.onDone
  • 我会在休息后像这样实现它,如果它有效,我会将您的答案标记为已接受。我在查看文档时一定忽略了 onDone() 函数。
猜你喜欢
  • 2020-01-07
  • 2016-12-30
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 2019-02-24
  • 2021-09-30
  • 2021-04-18
相关资源
最近更新 更多