The concept of Hierarchical Dependency Injection in Angular, as explained in the guide here, invites us to view DI as a combined logical tree.
Explaining the use of the @Host()
modifier, the guide mentions that it restricts the search scope to the <#VIEW>
level of the logical structure. It provides an example using @Host()
along with @SkipSelf
and @Host
.
<app-root @NgModule(AppModule)
@Inject(FlowerService) flower=>"🌺">
<#VIEW> <!-- end search here with null-->
<app-child @Provide(FlowerService="🌻")> <!-- start search here -->
<#VIEW @Inject(FlowerService, @SkipSelf, @Host, @Optional)=>null>
</#VIEW>
</app-parent>
</#VIEW>
</app-root>
The guide then introduces the usage of viewProviders
, which ensures that the dependency is available within the <#VIEW>
. An example demonstrates successful resolution when the dependency is provided in the AppComponent
through the viewProviders
array.
<app-root @NgModule(AppModule)
@Inject(AnimalService=>"🐳")>
<#VIEW @Provide(AnimalService="🦔")
@Inject(AnimalService, @SkipSelf, @Host, @Optional)=>"🦔">
<!-- ^^@SkipSelf() starts here, @Host() stops here^^ -->
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService, @SkipSelf, @Host, @Optional)=>"🐶">
<!-- Add @SkipSelf ^^-->
</#VIEW>
</app-child>
</#VIEW>
</app-root>
According to the analogy presented, providing a dependency via the providers
option while using the @Host
modifier in the component's constructor
brings us to create a logical tree like this:
<app-root>
<#VIEW>
<app-child @Provide(AnimalService="🐶")>
<#VIEW @Inject(AnimalService, @Host, @Optional)=>null> <!-- start and end search here with null-->
</#VIEW>
</app-parent>
</#VIEW>
</app-root>
However, there seems to be confusion on how the <app-child>
is reached, given that @Host()
should limit the search boundary to the <#VIEW>
, preventing further injections. What might be missing from this understanding?
For a visual demonstration, refer to the StackBlitz demo.