Angular inject

Explore Angulars inject function, possible use cases, and anti-patterns

Kevin Kreuzer
7 min readJun 28, 2022

--

Angular v14 contains many great features. Besides standalone components and typed forms, the inject function was one of the most talked-about features on Twitter. But what is it all about? Let’s find out?

In a nutshell, the inject function is a function that allows you to inject an Injectable. And well, it’s nothing new; in fact, it has already existed since Angular v9. But its use case was limited.

Inject function in Angular 9

We could use the inject function either in a factory function when declaring a new InjectionToken or inside the provider’s array of anInjectable. Let’s take a look.

Usage of the Inject function in Angular v9 inside the factory method of an InjectionToken.
Usage of the inject function inside the provider’s array of an Injectable.

Okay, got it. So what changed with Angular 14?

Inject function in Angular 14

With Angular 14, the use of the inject function is no longer limited to factory functions. From now on, you can use the inject function in your components, directives, and even pipes.

Cool, so what does that look like?

Imagine you have a CustomersComponent that displays a list of customers. The customers are provided by a CustomerService which is injected in the CustomersComponent constructor.

Classic constructor injection of a CustomerService.

Good old dependency injection via constructor. Nothing special. So let’s go ahead and refactor this code to use the new inject function.

Injecting the CustomerService with the new inject function.

We inject the CustomerService without the usage of a constructor. We use the inject function to directly assign the injected…

--

--

Kevin Kreuzer

Passionate freelance frontend engineer. ❤️ Always eager to learn, share and expand knowledge.

Recommended from Medium

Lists

See more recommendations