I'm trying to share a service between a parent component and it's child, and I was wondering what is the functionality of viewProviders. What is it's difference with providers ?
The viewProviders defines the set of injectable objects that are visible to its view, DOM children. They are not visible to the content children. At the component level, you can provide a service in two ways: Using the providers array.
providers: Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
The purpose of the providers array of an Angular module is to define the set of: libraries used by the application including Angular system and third-party libraries.
Lets take this example
class Greeter {
greet(name:string) {
return 'Hello ' + name + '!';
}
}
@Component({
selector: 'greet',
viewProviders: [
Greeter
],
template: `<needs-greeter></needs-greeter>`
})
class HelloWorld {
}
In the example, there is no difference between providers and viewProviders because HelloWorld's template doesn't use <ng-content>
. If you were projecting content within <ng-content>...</ng-content>
, then Greeter couldn't be injected in the projected content because you're using
viewProviders: [Greeter]
If you wanted Greeter to potentially be injected into the projected content, you'd use
providers: [Greeter]
So viewProviders
limits the provider to children other than projected content, while providers
allows all children to use the provider. The value is that viewProviders
allows you to prevent projected content from messing with your services, which could be especially useful in libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With