Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Component.providers and Component.viewProviders?

Tags:

angular

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 ?

like image 299
Mohammad Niazmand Avatar asked Mar 05 '20 05:03

Mohammad Niazmand


People also ask

What is viewProviders?

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.

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 the purpose of the providers array of an Angular module?

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.


Video Answer


1 Answers

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.

like image 133
Sanjay Lohar Avatar answered Oct 23 '22 10:10

Sanjay Lohar