The Angular pattern that needs no Provider
Services are often the default abstraction for reusable Angular logic. But what if the logic is local to a component, depends on its injection context, and does not represent shared application state? Consider a dashboard widget that knows whether its host element is currently visible: @ Component ({ selector : ' app-dashboard-widget ' , template : ` <p>{{ visible() ? 'Awake' : 'Sleeping' }}</p>…
When a component needs to know if its host element is currently visible, a commonly used solution is to create a services. However, this approach might be overkill if the logic is local to the component and doesn't represent shared application state. Consider a dashboard widget that uses this information to avoid rendering expensive parts of the template or pause/resume asynchronous processes.
A more efficient solution would be to use a host directive. This encapsulates the functionality without requiring additional provider configuration. By adding the host directive to the component’s metadata, the feature becomes a contextually available signal tied to the component's own lifecycle. While this approach still requires a small amount of metadata boilerplate, it avoids the need for another injectable instance and eliminates the risk of forgetting to declare a provider.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.