Urgent.News

One page, thousands of outlets. See who else covered it.

Editions

Tech

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.

Read the original at dev.to →

More in Tech

What are you working on? #01

What are you working on? I hear these words in my day-to-day. And sometimes, when I hear them, there’s this little brain freeze that happens because my brain is probably trying to put into words the…

More from Sunday 16 August →