Angular animate before routing

2020-07-27 05:44发布

问题:

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>

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?

Thanks and cheers!

回答1:

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.

Here is an implementation example :

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

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

Here is a running example with this suggested solution.

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.