Adding Suspense to Angular! 🕵️‍♂️

Netanel Basal
Netanel Basal
Published in
3 min readJul 1, 2020

--

I see a lot of enthusiasm lately in the React and Vue communities for the Suspense API. Suspense offers a component that allows you “wait” for some code to be rendered, and declaratively specify a loading state (like a spinner) which is displayed until then. Here’s an example from Vue:

If you’re not familiar with Suspense, I recommend reading these articles.

Seeing this, I told myself I’d try to do something similar in Angular. In this article I want to share what I’ve ended up creating, which took me about 20 minutes to make 😀

The approach I took is similar to the one Vue uses, since it more resembles Angular. Here’s what we want to achieve:

We want to show the fallback view while we’re fetching the users component and waiting for the setup() method to complete the asynchronous work it needs to do. When these both have occurred, we render the component. If an error occurs in the process, we render the error view instead.

If you’re not familiar with lazy loaded components with Ivy, I recommend reading the following article:

Let’s get started. First, let’s create the defaultView directive:

This is a simple directive that takes as input the factory function that fetches the component. Let’s move on to the fallbackView directive:

The sole purpose of this directive is to expose a reference to the template, so that we can use it in the parent suspense component. The errorView directive works the same way:

Now let’s see the suspense component:

We obtain a reference to each of the directives we’ve created earlier. We also obtain a reference to a ViewContainerRef, so that we can add the component to the view.

The next steps are as follows: Create the fallback view, fetch the component, create it, and wait for the setup() method to complete its work. Then, clear the view and render the component. In case of an error, render the error view instead.

And that’s all. Let’s see it in action:

Refreshing….

I also took it a step further and added support for non-lazy components:

In the above example, it’ll wait for both components to finish their setup() and then render both.

You can see the complete code in this repo. I know I probably missed a few things, remember it was quick and dirty work 🤓

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.