TLDR:
Use Ngrx Actions in order to pass data or initialize process inside components, keeping them completely decoupled.
The Issue:
With applications getting bigger and bigger we as developers need to find better solutions for passing data into our components and services, and this is where things get messy. When we look at Angular’s solutions we can see the upcoming growing pains.
Nothing wrong with using the solutions mentioned above. but we can do better.
Opinionated Solution
Ngrx is an amazing solution for storing and sharing data in our applications. In many applications, it becomes the single source of truth (as it should) and is used mainly to make our UI react to data store changes as we go. Yes, we want to update our UI when the data we depend upon changes. But why stop at data changes? Why not “abuse” Actions?
Actions are our way to update our store and to initiate a process. We usually use an *EffectsService and/orreducers for this. in which we listen to specific actions and run higher-level functions (HTTP calls for example, or normalizing the data before setting it in the store) in order to update our store and make our application react accordingly.
Fortunately, most Angular elements (Component/Services/Directives ) can listen to actions. this means that almost any element can listen to predesigned Actions made for it.
For example, if we have a button component, that listens to an action called ButtonLoaderAction and its props are props<{loading: boolean}>. The button is agnostic, it is decoupled from any other logic. it is completely independent, it will only update when the action is called by whoever calls it.
Actions don’t do anything but send events to anyone listening to it, usually our reducers and/or effects, we can take advantage and use them in order to make our website react not only to data changes but to developer decisions. We decide when our application reacts and changes.
Passing the power, of when our application reacts, to the developer is already an emerging concept with updating the changeDetection strategy to onPush for example.
Isn’t this a bit overkill?
With Micro front ends being all the buzz right now and web applications are required and expected to do more and more, we need to find higher-level / less decoupled solutions for making our application behave the way we expect and want them to.
Scale and easy development is the guiding thought, Actions are native js functions with nothing smart about them, creating hundreds of them won’t harm your application’s performance, thus we can enjoy an easier development experience.
Benefits:
Downside:
Notes:
This is purely my opinion, which was tested on a very large code base with micro front ends and worked better than I could have imagined. Performance was not hindered but even improved. Hopefully, all of you can enjoy and start this trend which I personally am going to implement from now on.