路由前的角度动画 [英] Angular animate before routing

查看:23
本文介绍了路由前的角度动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我试图摆脱路由时跳过的 Angular 动画.在我的模板中,我在 css-grid 布局中使用 mat-card 获得了不同的小部件",我想让它平滑地出现和消失.

In my current project I'm trying to get rid of Angular animations skipping when routing. In my template I have got different "widgets" with mat-card in a css-grid layout which I want to make appear and disappear smoothly.

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

My animations in the child component (to which the route points to) are looking like

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'))
  ])
]

简化的模板看起来像这样

The simplified template looks like this

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

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

卡片随动画一起出现,但路线直接更改到下一条路线,而无需等待动画.我还在过渡内的 query 中使用 animateChild() 进行了测试,但这无济于事.如何让路由器等待它们?

The cards appear with animations but routing directly changes to the next route without awaiting the animations. I also tested using animateChild() within a query inside a transition, but that does not help. How can I make the router wait for them?

谢谢和欢呼!

推荐答案

当路由改变时,组件被销毁并且不能再被动画化.如果您想在组件被销毁之前对其进行动画处理,您可以使用 CanDeactivate 守卫,以确保该组件可以在销毁之前被停用.

When a route changes, the component is destroyed and cannot be animated anymore. If you want to animate the component before it gets destroyed, you could use a CanDeactivate guard, that makes sure that the component can be deactivated before destroying it.

这是一个实现示例:

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

然后在路由模块声明中:

Then in the route module declaration :

RouterModule.forChild([
      { path: '', component: HelloComponent,
  canDeactivate: [CanDeactivateGuard] }
])

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

After that you can make use of ngOnInit and canDeactivate to play the start and end animations :

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();
}

以下是此建议解决方案的运行示例.

为了简单易用,我制作了一个处理动画的抽象组件,通过简单地扩展抽象组件来将动画行为添加到任何组件.

To make it simple to use, I made an abstract component that handles the animations, to add the animation behavior to any component by simply extending the abstract component.

这篇关于路由前的角度动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆