What is viewProviders in the below code? And how it differs from providers?
class Greeter { greet(name:string) { return 'Hello ' + name + '!'; } } @Component({ selector: 'greet', viewProviders: [ Greeter ], template: `<needs-greeter></needs-greeter>` }) class HelloWorld { }
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. Using the viewProviders 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.)
Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers is used to register the classes to an angular module as a service. And then, this service classes can be used by other components during the itself creation phase in the module.
The new dependency injection system in Angular comes with a feature called “Multi Providers” that basically enable us, the consumer of the platform, to hook into certain operations and plug in custom functionality we might need in our application use case.
In your 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