Avoid passing input properties through many levels with content projection

Wojciech Trawiński
JavaScript everyday
2 min readNov 13, 2018

Some time ago I was preparing for a job interview during which I was supposed to answer question concerning both Angular and React. Since I hadn’t used React for a couple of months I decided to brush up on my knowledge and spent some time with the docs. I came across the following sentence:

“If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.”

As far as the Angular world is concerned, the simpler solution is called content projection.

Introduction

In this article I’m going to show you a simple example on how to avoid having property chains with the aid of content projection. Since, the example is based on a real world complex application, I will simplify both the layout and provide mock data instead of using ngrx/store.

The application renders the exercise-screen component which is a smart container providing models for views.

Dumb components include:

  • version-info component responsible for rendering an image with description appropriate for the given version (for the sake of simplicity it’s just a placeholder with the version name),
  • exercise-header component which receives a config with exercise data and application version type in order to pass it down to the version-info component,
  • cool-exercise-header-component which receives only a config with exercise data and has a content projection slot for the version-info component.

Implementation

Let’s start with the data provider, namely the exercise-screen container

Without the use of content projection you need to pass the version data to the exercise-header component

just to pass it down to the version-info component

whereas the cool-exercise-header component requires only the config data and renders the version-info component with the aid of content projection

Conclusion

Although the final result is the same for both approaches, it’s a far better solution to make use of transclusion, since the code is more readable and easier to reason about.

The benefit of the approach is much more noticeable when you need to emit events up through many levels. In addition, the time required to perform the change detection will be shorter, since less method calls is necessary.

Like, love, hate, clap!

--

--