Angular — Route transition Animation, change page back and forth (v5)
How to animate your page change using the Angular Animation
📝 I have written new article about same animation with new implementation, which is improved, using less code and more efficient. Have a look at : Angular 7 — Improved Router Transition Animation
I have seen lots of Angular animation examples online and especially route change animations were my point of interest. I have found several tutorials, but none of them completely helped me to implement back and forth animation on the page change, which was what I wanted.
Example Application
I have created simple demo app which contains the simple page change animation. Page slides on the left or right depending on which page you are at and where you want to go. I have two tabs and page change triggers animation. It is possible to have as many tabs as I wish and all the tabs will have correct animation.
Example app and source code on StackBlitz
TL;DR
I use my navigation service class to catch all router change events and take router snapshot data, then store the last and new values. I have custom logic to trigger 0, 1 or 2 indexed animations based on the snapshot data num property value.
This is one of the animations which responsible to changing page from left to right, there are two more animation logic one of them is responsible for changing page right to left. The third one is same as the one displayed here, but it has responsibility to display animation after page refresh when there is no previous value, also one of the animation already happened and needs to be repeated. (If you tell Angular to display animation indexed 1, two times consecutively, It won’t, because it works like distinct until changed)
You need to attach custom data to the routes so that getAnimationNumber function knows that page which is coming next is located after the current page, so that correct animation triggers. I can add more pages and enumerate them correctly to have animation which feels like moving from left to right or vice versa.
Animation needs to be added alongside the component where router outlet is located, in my case it is AppComponent. routerTransition function from animation.ts is imported and used inside Component declaration. getRouteAnimation returns the new index of animation which will be rendered when page change happens.
One last bit is to add div to html which wraps the router outlet. It needs the method which returns the new state every time page change happens.
You can read more about Angular animations on their website to create more complex and beautiful animations: 💻 Official Angular Animations api
📝 My new improved implementation of this animation : Angular 7 — Improved Router Transition Animation
If you don’t understand something feel free to ask me for any help you might need, I will be more than happy to help any of you. Please leave the feedback. Angular ♥