With Great Angular Components Comes Great (Single) Responsibility

Netanel Basal
Netanel Basal
Published in
2 min readMay 10, 2021

One of the recent requirements in our application was to create a dynamic actions menu component that takes a list of actions and displays them inside a popover.

The component can be rendered multiple times, as part of different views. One of the views is a cell renderer inside our grids. In such a case, we need to run some specific functionality when we toggle the visibility of the menu. One way to solve this is to use an input that will indicate if we’re in a grid context:

I’m skipping the implementation of the component because it’s not relevant to this article. We’ll discuss it in a future one.

To be honest, I’m not very happy with this implementation. Let’s stop for a second and think about it. Is this the responsibility of the action menu component? Does this component need to be aware of the grid? The answer is no. The single responsibility of the component is to get a list of actions, render and manage them.

To solve this issue, and clean our code, we’ll create a directive that’ll listen to the visibility output and run the code it needs. First, we need to expose the visibility output from our component:

Now we can create our directive:

Using the HostListener decorator, we can listen to the visible output that our actions menu component emits and run our code. Now we can add the directive only where we need to:

Now I’m happy 😃

Another thing worth mentioning is that we can also inject the action menu component in our directive if we need to. It works because they share the same injector.

🚀 In Case You Missed It

Here are a few of my open-source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailor — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

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

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

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

Responses (2)