Getting to know the ENVIRONMENT_INITIALIZER Injection Token in Angular

Netanel Basal
Netanel Basal
Published in
1 min readMay 19, 2022

--

The environment injector is a generalized version of NgModuleRef, which is also known as the “module injector”. It’s one of the primitives required to support standalone components APIs introduced in Angular v14.

We can currently use NgModule to run some initialization logic, for example:

We can now achieve the same result without using NgModule using the new multi-token ENVIRONMENT_INITIALIZER:

The code registered with this token will be executed during the application’s initialization.

Additionally, when we navigate to a lazily loaded route, the router creates a new EnvironmentInjector for the route. Therefore, we can also provide ENVIRONMENT_INITIALIZER on a lazy route, and it’ll only be executed upon navigation:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.