ViewProviders in Angular

ViewProviders are similar to Providers except that the dependencies that you define are visible only to its view children. They are not visible to the Content children.  

ViewProviders Example

Look at the example app at stackblitz

The app has RandomService, which generates a random number when initialized.

random-service.ts

ChildComponent displays the random no from the RandomService.

It also has ng-content, where the parent can inject content. The Parent component is going to inject the GrandChildComponent here.

ChildComponent also displays the GrandChildComponent as View

child.component.ts

GrandChildComponent just displays the random no from the RandomService. We use @Optional() decorator ensures no error is thrown if the dependency is not found.

grand-child.component.ts

In the AppComponent, we display the ChildComponent. We also project the GrandChildComponent inside the ChildComponent using projected content.

app.component.ts

Run the app and you will see all the components receive the same value for the random no. Because the RandomService is provided from the root module injector.

Also, note that ChildComponent displays the GrandChildComponent twice. Once as a Content Child (Projected Content) and also a View Child.

Add the RandomService to the Providers array of the ChildComponent. As you can see from the image below, ChildComponent and all its children (content children and view children) gets the instance of the RandomService provided by the ChildComponent.

ViewProviders in Angular Example

Now, move the RandomService from Providers to ViewProviders. As you can see in the image below View Child still get the RandomService from ChildComponent, but the Projected Content does not. Projected Content gets the service from the Root Module.

Projected content ignores the ViewProviders

The providers allow all children to use the services. While the viewProviders limit it to children other than projected content.

Use case for ViewProviders

This is useful when you develop libraries.

For Example, you have made some-great-comp , which user will be using it to project their user-component into it.

Here you do not want services that you used in your some-great-comp interfere with the user-component. Hence you provide your services in the ViewProviders.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top