Leverage Angular’s Element Injector to make DRY Inputs

Netanel Basal
Netanel Basal
Published in
2 min readJul 19, 2021

--

In our application, we have created a multi-select component. In most cases, we use the default design and functionality. There is a particular case where we need to show key-value options in our multi-select component, and we use it in multiple places across the application:

We need to set a custom option template, placeholder, chip text, search strategy, label key, and id key in this case:

One strategy to make it reusable is to create a dedicate KeyValueSelectComponent that wraps the multi-select component, but I prefer to avoid it when possible. You can read why in the following article:

As I see it, we have two concerns. First, we need to make the option template reusable. We’ll solve it by creating a component:

Next, we need to find a way to make our inputs DRY. Luckily, Angular provides a powerful feature — the Element Injector. Components and directives on the same element share an injector. That means that we can create a directive that injects the MultiSelectComponent and sets the inputs it needs:

Now when we need to use this type of select, we can use the directive and the component while keeping it DRY and flexible:

🚀 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!

--

--

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