Angular 动画:如何动态设置过渡时间?

Angular Animations: How to set transition timing dynamically?

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

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

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

以动态方式实现转换计时的最佳方法是什么?

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

在您定义的组件中

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 或...