Show loading animation at the right place in a list of links

·

2 min read

A loading animation is easy to set up in Angular by subscribing to router events. But how do you show it by the clicked link in a list of links?
I scratched my tired head, which eventually came up with a solution

When the user clicks a link, and the response is not immediate, it is a good idea to show an animation. For instance, in a weather app the user clicks a link to show the weather for tomorrow and the app has to query one or two APIs. While the resolver is waiting for the data to complete the user is left all alone and confused. A loading animation clears the confusion.

I found myself having a lot of links like 30 or so in a list. So where do you show the loading animation? If the user is on mobile, not much more than links will be visible on the screen. If the loading animation appears above the list of links, all the user will see is the links suddenly jumping down, while placing it below the user would have to scroll down to see it. The ideal place should be right below the clicked link.

There are a lot of ways to solve this. In my case I didn't want to use CSS and z-index, which may be the first idea that comes to mind. Instead, I created a component for the link which takes the link (the url) as input. The loading animation is placed inside this component, just below the link. And here comes the clever part, since you have access to the link, you can feed that to the loading animation. The loading animation subscribes to the router, so it knows where the navigation is going. And if that is the same place as the link, show the animation.
Code will be posted shortly.