Different Ways to Pass Inputs to a Component in Angular
In this article, we’ll look at three different ways we can pass data to a component. In the following examples, we’re going to use a core select
component, but these methods are relevant to any component.
Let’s create a select
component that receives a size
and placement
inputs.
Using Inputs
The first method that we’re all familiar with is using the Input
decorator:
That works great, but it’s not so flexible. Let’s say we want to set the size
input to large
for any select
in our application. Using this method, we can’t do this. We should allow the consumer to override any input at a global level.
Using Dependency Injection
To do so, we can make use of Angular’s dependency injection feature:
First, we need to create a config provider. This provider can be used as a token
, a type
and it also provides default values for each input
. Let’s use it in our select
component:
Now we can override the select’s inputs
at the application level:
But that’s not all. We can also use it to provide different inputs
at the component level. Let’s say we have a page that uses the component several times. In each one, we need to use a small
size:
We can add it to the component providers
, and it’ll be used for any components declared in its template and his children. We can still override it using a direct input
if we need to:
The same strategy applies to lazy modules because they create a new injector.
Using Directives
Let’s say we have a component with many inputs. In many places (not all of them) where we consume it, we’re using the same set of values. If we use our example, it’ll be something like:
We can repeat ourselves in each place, or we can create a directive that provides this configuration and serves as our single source of truth:
And we can use it where we need to:
Please come up with a better name for the directive 😀
You can play with the code in ng-run.
🚀 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
- Forms Manager: The Foundation for Proper Form Management in Angular
- Cashew: A flexible and straightforward library that caches HTTP requests
And many more! Checkout ngneat.
Follow me on Medium or Twitter to read more about Angular, Akita and JS!