All topics
Servicesadvanced

Resolution Modifiers

Explain @Optional, @Self, @SkipSelf, and @Host and how they change how the injector tree is searched.

The four resolution modifiers — @Optional, @Self, @SkipSelf, and @Host — let a class fine-tune exactly how the injector hierarchy search behaves for a specific dependency, and they're a favorite advanced interview topic precisely because they're rarely used day-to-day but reveal a deep understanding of the injector tree when explained correctly.

Default DI search is like asking your question up the entire management chain until someone can answer; @Self is refusing to ask anyone but your direct desk-mate; @SkipSelf is deliberately skipping your desk-mate and asking only your manager and above; @Optional means you're fine getting a shrug and moving on if nobody has an answer.

Key Concepts

1
@Optional() tells Angular not to throw an error if no provider is found for the token, resolving to null instead — useful for genuinely optional integrations, like an analytics service that might not be configured in every environment. @Self() restricts the search to only the requesting component's own injector, refusing to walk up to ancestors at all, which is useful when a directive needs a dependency that must have been explicitly provided at exactly that element, not inherited from somewhere higher up.
@Optional()null@Self()
2
@SkipSelf() does the opposite of @Self() — it skips the current injector and starts the search at the parent, which is the classic mechanism for building a tree of communicating instances of the same service type, like a nested comment thread where each level needs to know about its parent's instance specifically (not its own). @Host() limits the search to stop at the current component's host view boundary, relevant mainly for directives applied within a component that shouldn't reach past that component's own template into the wider application tree.
@SkipSelf()@Self()@Host()
3
These modifiers can be combined (@Optional() @SkipSelf() is a common pairing, meaning "look starting from my parent, and it's fine if nothing is found"), and interviewers sometimes ask you to design a recursive tree component (like nested comments or a file explorer) using @SkipSelf() specifically, since it's the cleanest real-world example of why these modifiers exist at all.
@Optional() @SkipSelf()@SkipSelf()