Search⌘ K

Restricting DI Down the Component Tree

Understand how to restrict dependency injection in Angular to specific components within the hierarchy. Learn to use viewProviders and decorators such as @Host, @Optional, @Self, and @SkipSelf to manage service accessibility and injector behavior. Explore advanced provider configurations for overriding instances or injecting non-class types.

We saw how ProductListComponent registered ProductsService, making it immediately available to all the child components. A component may contain child components at different levels. That is, its child components can have other child components, and so on. Sometimes, we might need to restrict dependency access to components located next to a specific component in the hierarchy. We can do that by registering the service in the viewProviders property of the @Component decorator:

TypeScript 4.9.5
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css'],
viewProviders: [ProductsService]
})

In the preceding snippet, we define that ProductsService should only be accessible by the injectors of the ...