Keeping Your Angular Components DRY With Content Projection

Don’t Repeat Yourself

Jamie Morris
The Startup

--

Photo by Erik Witsoe on Unsplash

There is a concept in software development called DRY: Don’t Repeat Yourself. It means that you should reuse functionality rather than writing it from scratch. I often see this principle ignored when it comes to building components, though, which is odd, since that’s exactly what components are there for.

There are two things that change from one component to the next in your application: Behaviour and Content.

When behaviours change, you need to write new functionality to express those behaviours to the user. Two behaviours don’t often share the same content, but it is commonplace for the same behaviour to be used in multiple places.

Building a Modal

Take a simple use case — the humble modal. One modal alerts the user that they need to register and presents a form to do so. Another modal displays information about a product they clicked on.

The behaviour in both cases is similar: present content to the user in a modal that can be dismissed with a click. Each modal is styled the same, but the content is subtly different. Let’s take a look at how the code might look for both:

--

--

Jamie Morris
The Startup

I used to be a full stack developer, but nowadays most people only want me for my <body>, so I try to be a UI expert. All opinons are my own, not my employer's.