Angular & Dependency Injection: tricks with Decorators

Michele Stieven
5 min readAug 24, 2021

Every Angular developer knows about its awesome Dependency Injection system… but not everyone knows all of its features! Let’s take a look at some interesting tricks which might come in handy!

Parameter Decorators

In Angular, thanks to TypeScript, we have multiple types of decorators, the most known are:

  • Class Decorators (which decorate a class, for example: Component, Directive, Injectable…)
  • Property Decorators (which decorate a property, for example: Input, Output, ViewChild…)

There is however a third type which is used less often, but it’s just as useful: Parameter Decorators! They’re decorators which we can apply to our dependencies (the ones we place in the constructor of our classes). They’re not used too often, because thanks to Angular we just need to say which class we want to inject and Angular uses the class’ name to give us the right instance. But they’re not useless at all!

These are the Parameter Decorators we’ll look at in this article, every one of these is imported from @angular/core:

  • Self
  • SkipSelf
  • Optional
  • Host
  • Inject

--

--

Responses (1)