Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are viewproviders in Angular? And what is the difference b/w providers vs viewproviders?

Tags:

angular

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 { } 
like image 322
Vikram Babu Nagineni Avatar asked Mar 09 '16 10:03

Vikram Babu Nagineni


People also ask

What is viewProviders in Angular?

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.

What are providers in NgModule?

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.)

What is providers used for in Angular?

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.

What is multi in provider Angular?

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.


1 Answers

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.

like image 111
Mark Zamoyta Avatar answered Oct 03 '22 23:10

Mark Zamoyta