路由前的角度动画

ngf*_*ixl 2 animation angular-routing angular angular-animations

在我当前的项目中,我试图摆脱路由时跳过的 Angular 动画。在我的模板中,我在 css 网格布局中有不同的带有mat-card 的“小部件” ,我想让它们平滑地出现和消失。

我的子组件中的动画(路线指向的)看起来像

animations: [
  trigger('cardAnimation', [
    state('void', style({ opacity: 0, transform: 'scale(0.5)' })),
    state('*', style({ opacity: 1, transform: 'scale(1)' })),
    transition('void => *', animate('500ms ease-in')),
    transition('* => void', animate('500ms ease-in'))
  ])
]
Run Code Online (Sandbox Code Playgroud)

简化后的模板如下所示

<mat-card @cardAnimation>
</mat-card>

<mat-card @cardAnimation>
</mat-card>
Run Code Online (Sandbox Code Playgroud)

卡片会显示动画,但路线会直接更改为下一条路线,而无需等待动画。我还测试了animateChild()query过渡内部使用,但这没有帮助。如何让路由器等待它们?

谢谢并欢呼!

ibe*_*oun 6

当路线发生变化时,组件将被销毁并且无法再进行动画处理。如果您想在组件被销毁之前对其进行动画处理,则可以使用CanDeactivate防护装置,以确保在销毁组件之前可以将其停用。

这是一个实现示例:

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在路由模块声明中:

RouterModule.forChild([
      { path: '', component: HelloComponent,
  canDeactivate: [CanDeactivateGuard] }
])
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用ngOnInitcanDeactivate播放开始和结束动画:

ngOnInit() {
  this.animation = this._builder.build(this.slideIn(this.ANIMATION_TIME));
  this.player = this.animation.create(this.el.nativeElement, {});
  this.player.play();
}

canDeactivate() {
  this.animation = this._builder.build(this.slideOut(this.ANIMATION_TIME));
  this.player = this.animation.create(this.el.nativeElement, {});
  this.player.play();
  return timer(this.ANIMATION_TIME).pipe(mapTo(true)).toPromise();
}
Run Code Online (Sandbox Code Playgroud)

这是使用此建议解决方案的运行示例。

为了使其易于使用,我制作了一个处理动画的抽象组件,只需扩展抽象组件即可将动画行为添加到任何组件。

  • @Jago 已修复,该示例很旧并且遵循旧的角度项目树。 (2认同)