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

问题描述

在我当前的项目中,我试图摆脱布线时跳过的Angular动画。在我的模板中,我想通过css-grid布局中的 mat-card 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'))
  ])
]

简化的模板如下:

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

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

卡片与动画一起出现,但直接路由到下一条路线而无需等待动画。我还测试了在过渡内的查询中使用 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] }
])

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

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.

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

07-30 19:17