Sharing Top Content from the Angular-sphere.

@Self or @Optional @Host? The visual guide to Angular DI decorators.

  • The default injection — just enough for 99% cases™By default Angular will first check if the component defines a dependency injector in its decorator.
  • , but also not necessarily: if your component doesn’t absolutely need that service, you can decorate a parameter with the @Optional() decorator and in such case of no provider found, no error will occur.
  • @Host()@Host() decorator makes Angular to look for the injector on the component itself, so in that regard it may look similar to the @Self() decorator (7.)
  • In that case it can be used on a Component that defines its injector and that component would be the directive’s host.Or we can have our KidComponent projected into ParentComponent(by that ng-content/ng-content thingy).
  • Then we also say that our component is being hosted by ParentComponent — and if ParentComponent provides ToyService and KidComponent does not, the @Host() decorator of that inner component would still get that service’s instance (8.)

Most of the time, when we need a service injected into our Angular classes, we can rely on the default service lookup that the framework provides. But that’s only, well, a default — and Angular also…

The defaultLet’s look at a sample KidComponent. It needs to know about toys that are being kept in a ToysService, so we inject that into its constructor (usually with a private modifier, here omitted for brevity).The default injection — just enough for 99% cases™By default Angular will first check if the component defines a dependency injector in its decorator. If it does (1.), the component (specifically: each of its instances) will receive its own instance of the service. If it doesn’t find in on the component, it will look for a parent injector (e.g. the parent component (2.), its ancestors etc), up the injectors tree and in the end it will stop on the application-wide instance of the service defined on a one of our NgModules. Unless it’s not even there, in which case we will get a “No provider” error.@Self()If we decorate the parameter with @Self(), it’s like there was only the first step of the previously discussed default behaviour. The only place allowed to find the injector is the component itself (3.). If it isn’t defined there…@Optional()… well, that would be an error, right? Yes, definitely (4.), but also not necessarily: if your component doesn’t absolutely need that service, you can decorate a parameter with the @Optional() decorator and in such case of no provider found, no error will occur. Instead Angular will set the value for our service tonull(5.)You can set @Optional() in any other DI scenario discussed here as well.If you’re following, in our Angular code, this could actually…

@Self or @Optional @Host? The visual guide to Angular DI decorators.