Inverting the control to make super reusable components!
Tags: javascript, angular, html, components
Published: 2019-10-27 15:57:24

(originally posted on [Medium](https://medium.com/@phenomnominal/inverting-the-control-to-make-super-reusable-components-fff30944a9d7))

Component architecture is pretty hard! Without strict discipline, you can fall into really bad habits. You forget everything you know about building software, and write confusing, unmaintainable code. The application started small, but then it grew and the requirements changed… Now it’s out of control! 🔥🦖🔥

Inevitably, there comes a point where our components are far too big, and we need to break them down a bit. But is there a way that we can redesign and refactor our components for long term flexibility? I think the answers lie in design patterns like [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection), and [Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control)!

##TL;DR; 🤯

Can’t be bothered reading the whole article? Here’s the gist in a handy tweet sized snippet:

> ## Apply Inversion of Control when building components! Decompose your components into small units. Then compose them together rather than making “god” components. They’ll be easier to reuse, easier to extend, and easier to reason about. Works in React❤️, Vue❤️, or Angular❤️ ! Cool!

Want more details? Read on… ❤️

##Card: first attempt — one big component 🌟

Let’s imagine a card component like the following:

![A cute little card component](https://thepracticaldev.s3.amazonaws.com/i/otmz57wto0peg3a94avx.png)

How can we implement it in a way that means it will be easy to modify as our requirements change?

Here’s an initial implementation of the card in StackBlitz! I’m going to stick with Angular for all these examples, but the concepts can apply to any Framework! Jump in and take a look at how it works:

{% stackblitz card-v1 %}

Here's the HTML template for a first attempt at the card component. It contains everything that our component needs to render correctly.

{% gist https://gist.github.com/phenomnomnominal/20234957b92585ce56bd02b434ad8385 %}

This is already quite a large component! We know that large components can be difficult to change. One way that we could make the card more maintainable is by splitting the card up into a few smaller components.

##Card: second attempt — breaking it up🌟🌟

It might make sense to break our **`<my-card>`** component into three parts:

* **`<my-card-image>`**
* **`<my-card-title>`**
* **`<my-card-details>`**

And then update our card component to use the new components:

{% gist https://gist.github.com/phenomnomnominal/8a195f60646775ef39e6b7fdac364de0 %}

Here’s a StackBlitz implementation of the more modular card:

{% stackblitz card-v2 %}

This is better! It looks the same, but there’s a clearer separation of responsibilities. This card is definitely going to be easier to reason about. Job well done 🎉! But…

##Card: third attempt — new requirements 🌟🌟🌟

What happens when we get a bit further down the road, and some of our requirements change. What if we have to handle an image *carousel* rather than one single image?

One approach might be something to add some more logic to the template so that it can handle a single image or many images. That might look something like this:

{% gist https://gist.github.com/phenomnomnominal/ce3b35cd9096e67d9a8345a0f62135bb %}

We’ve added the required functionality, and it doesn’t seem too awful. But then, once again, our requirements change and now we have to handle a *video* in our card…

We could add another **`*ngIf`** (even more logic) and move on, but it starts feeling pretty gross:

{% gist https://gist.github.com/phenomnomnominal/0df4d9bcedcb76d08488b010c405d94f %}

Let’s see what that looks like:

{% stackblitz card-v3 %}

This isn’t a particularly flexible way to add functionality to our card component. And unfortunately this will have a performance impact too! Our application bundle will include the code for all three different situations — even if we only use one at a time. As well as being inflexible, we’ve now got quite a bit of logic in our template. In the Angular world, we might want to move this logic to a service, and then write some tests to make sure we don’t break it in the future… but that still doesn’t sound great!

Let’s take a step back and think about what’s going on… 🤔🤔🤔

##Improving flexibility with Dependency Injection 💉

The problem we have is that **`<my-card>`** knows too much about how to create itself! This is something that we may have come across in our JavaScript/TypeScript code:

{% gist https://gist.github.com/phenomnomnominal/0c9f91f3ad605a6621365a4d4fad1e70 %}

There’s nothing super bad about this, but it’s inherently inflexible. What happens if we want to swap out the engine for an electric motor? Or replace the automatic transmission with a manual one?

The usual way to handle this kind of thing is to use a pattern called “[Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control)”. The Angular framework heavily relies on the IoC pattern. The constructor of a class describes the *shape* (or **`interface`**) of its dependencies. The framework’s powerful [Dependency Injection system](https://angular.io/guide/dependency-injection) handles the rest:

{% gist https://gist.github.com/phenomnomnominal/072c0224b68d8acf7cec6c8aaebda242 %}

Now we can swap out our dependencies as we like, as long as they match the required interfaces! This makes our code much more flexible, and more testable. 🎉🎉🎉

So how do we apply this same inversion to our template code?

##Card: fourth attempt — dependency injection for components using content slots 🌟🌟🌟🌟

Another way that we could re-architect the **`<my-card>`** component is by adding *content slots*. We do that with one of my favourite Angular features, **`<ng-content>`**. Each slot is analogous to an argument for the “constructor” of the component template. The **`select`** attribute is like the **`interface`** — it defines which content is inserted into which slot:

{% gist https://gist.github.com/phenomnomnominal/571428160a77991115ca420483bf333f %}

> ### I’m a huge fan of [this article](https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b) by [Eudes Petonnet](https://twitter.com/eudespv) that provides a tonne more information about **`<ng-content>`**! Check it out!

Now that we’ve got out code set up to use **`<ng-content>`**, we can use **`<my-card>`** like this:

{% gist https://gist.github.com/phenomnomnominal/c699044507e9476096d8dcc6c6da7505 %}

And if we have to swap out our image for a video we can use a different component in the slot:

{% gist https://gist.github.com/phenomnomnominal/3d0f6db371718a08217fb9d036634f87 %}

Here’s yet another StackBlitz implementation, showing the card with **`<ng-content>`** slots:

{% stackblitz card-v4 %}

The **`<my-card>`** component is now much simpler!

It now only defines the layout of the group of slots. Each of the inner components has to be able to take up all the space available to it. It is exactly like our TypeScript example! Except instead of a *metaphorical* shape (the interface), we have an *actual* shape that we need to fill. We’ve been able to split the HTML and CSS so that each component handles how it appears on the page. You might be thinking that it is quite verbose to repeat the whole structure over and over? Remember that we can still make a reusable wrapper component that encapsulates all the slots (for example, a **`<my-video-card>`**). The **`<ng-content>`** pattern gives more flexibility in finding the right level of abstraction.

We’ve simplified the TypeScript too! The **`<my-card>`** component no longer needs to know about data needed to render the card. The data is instead managed by the component that is constructing the contents for each slot. Instead of the **`<my-card>`** component being the orchestrater, the inner components receives the data. This is one of the most powerful parts of this pattern, which is that we’ve pushed most of our components further towards the “presentational” end of the component spectrum. Most of our components do very little. And we no longer have to pass data down through multiple layers of components.

Of course, this is a trade off. We have a lot more files that we began with. We had to define new directives for each of our slots so that the Angular compiler can understand them. And when we use the component, the markup is also more complicated. We have more components than we had before, which results in more DOM nodes. Excessing DOM nodes can have a compounding performance impact in a large application.

Is there anything we can do to reduce the complexity of using the component?

##Card: fifth attempt — taking it further (or maybe too far!) 🌟🌟🌟🌟🌟

We can simplify our component by using [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) instead of [type selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors). That might look something like this:

{% gist https://gist.github.com/phenomnomnominal/50b06debcfc245be8826c84d836a0617 %}

Here’s the final StackBlitz, if you want to see all the code:

{% stackblitz card-v5 %}

We’ve removed the extra elements, and the extra directives that define the content slots. Is this a better API? Is it clearer? Maybe! Maybe not! I’m not super sure. But it’s important to play with things like this when we’re designing component APIs. What do you think? Did we go too far? Not far enough? Please leave a comment, or [tweet me](https://twitter.com/phenomnominal) and share your thoughts!

##Summing up ➕

I’m a big fan of this pattern! I love how it aligns with the dependency injection pattern with TypeScript in Angular. I also love how the logic and moving parts melt away as we re-architect our code. It's great for anywhere where you need reusable components, such as in a component library. But I think it’s been particularly unused in applications!

Like most things, it’s a trade off, and if you’re not careful it can be a premature abstraction. But it’s definitely a useful tool to have in your toolkit, and I hope you find a need for it.

So please, try it out in your framework of choice! Build a few components that use content slots and let me know how you get on!

❤️🦄