While services and dependency injection are good, just like many good things in life, they can be over-used and become somewhat of an anti-pattern.
Why? Because of how change detection works in Angular. Angular has two modes for change detection: The default
mode and the onPush
mode. onPush
is an optimization that works if and only if you’re using input-driven components, also known as presentation components.
In other words, whenever you inject a service into a component, you prevent that component from using the optimized onPush
change detection mode. This is one of the reasons best practices recommend sticking with container components (service-driven components tied to specific use cases) and presentation components (input-driven ones that can be used and reused as they’re not connected to any service – and any business logic).
The more presentation components you create, the more reusable your code is, and the more change detection can be improved. The next time you inject a service in a new component, think again: Could I pass that data as @Input
(s) instead of injecting a service?
If so, congratulations: You just prevented your presentation component from falling into this anti-pattern.