Angular Progressive Image

Display a loading indicator, an error message, and keep the consistent dimensions

In this article we will create a progressive image.

In the context of this component progressive means:

show loading indicator when the image has not finished loading

show an error message if the image fails to load

force constant width and height to prevent browser from expensive layout re-flows

The end result will look like this

Angular Progressive Image

One of the best ways of designing a component is to think of its API first. Let’s decide how we would like to use the component.

Looks good. We’ve created a wrapper component, and three directives. User keeps the full access to the native image component, which will be useful if she wants to set [alt] or [title] attributes.

Now that we have designed the component’s API, let’s start implementing the component. First we create the component and its directives.

As is, the width and height are not bound to the CSS properties.

Layout Re-flow with Varied Image Sizes

Let’s fix that by using the @HostBinding decorator bound to the style.width.px . We’ll use the same decorator to bind the image’s src .

Next, we want the user to set the width and height only once, in the <app-progressive-image> . It should then propagate to all directives.

For this we have to use the @ContentChild decorator combined with the AfterContentChecked lifecycle hook.

This is great. The component forces the fixed size for all directives.

Layout Re-flow Prevented with Fixed Image Sizes

Everything works, but there is a lot of repetition. We can do better.

Notice that each directive follows the same interface of having width and height . We can generalize this common behavior in a Dimensions class, and query the directives with @ContentChildren instead.

To complete the refactor, we have to tell Angular to provide each directive when we ask for the Dimensions class token.