Why Angular 14’s new inject() function is so amazing?

Vlad Gheorghita
6 min readAug 10, 2022

As you have probably already read, Angular 14 shipped some very interesting features: typed forms (which can still be improved, see how here), standalone components, and, the focus of this article, the ability to use the inject( ) function during the so-called constructor phase.

Let’s break the above sentence in 2.

What is the inject() function

The inject() function takes an InjectionToken as a parameter and returns the value for that InjectionToken from the currently active injector. Basically, it’s another way to get a hold of a dependency other than using constructor injection. Here’s an example.

Simple use of the inject() function

Might seem like “it’s different, but the same”, but bear with me. You will see how powerfull this new mechanism really is.

What is the constructor phase

The constructor phase means the constructor function scope and field initializers. This means that you cannot call the inject() function inside @Input() setters or any other function or lifecycle hook. Here is an example to better understand it.

--

--

Vlad Gheorghita
Vlad Gheorghita

Written by Vlad Gheorghita

And the Internet said: let there be web development. Find me on twitter @browsepedia

Responses (10)