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!
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 :
Then in the route module declaration :
After that you can make use of
ngOnInit
andcanDeactivate
to play the start and end animations :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.