Stop Wrapping Angular Components

İlker Erhalim
JavaScript in Plain English
2 min readJul 15, 2021

--

Image by jacqueline macou from Pixabay

“I will use this thirty-part component with the same configuration again and again, so I should wrap it.”

Seems like a good idea at first glance, but it’s unnecessary and requires a lot of work.

So what can we do instead of wrapping it?

The short answer is directives with hierarchical injections.

I do my samples on PrimeNG (because it’s open-source, popular, and free) but the following examples can be applied to every angular component set that is developed via components and directives.

Let’s think you have an employee collection and you want to bind it in a select input, and you use this input in multiple components/pages.

If you want to use employee dropdown on multiple pages, you have some alternatives.

  1. Write the same code for every component that has employee dropdown.

It’s not a big problem if you’re using it for two or three pages, but using it on more pages can result in high costs for simple logic requirements that may be encountered in the future.

2. Write a service that gets & maps employee for select list.

This can be a good solution, now we can change the get data logic in one file and this change can apply to all employee dropdowns. But we still need to set p-dropdown’s config for every usage.

<p-dropdown
[options]="employees"
placeholder="Choose an employee"
[showClear]="true"
[filter]="true"
></p-dropdown>

If you write tests then you have to create mocks/spy of EmployeeService and write tests for every usage.

3. Wrapping component with a custom component (Please don’t do that)

This can feel like the perfect solution, but it requires a lot of work to do. You need to create documentation for other developers, you should support all inputs & outputs of the component that you are wrapping. Also if you wrap a form component (like the example) you have to implement the ControlValueAccessor interface.

4. Create a directive that manipulates the Component properties

In this way you can use employee dropdown multiple times, without re-writing the same code/parameters, you can change the default configuration values, and if you update the PrimeNG library, you support the new Inputs/Outputs of <p-dropdown> without doing anything.

More content at plainenglish.io

--

--