🚀 Unleash the Power of DI Functions in Angular

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

--

We can use Angular’s inject() function to obtain a reference for a token from the currently active injector. We can use it in the factory providers or services, for example:

You can read more about InjectionToken factory providers in this article:

Starting from Angular v14, we can also use the inject() function in components, directives, and pipes. It opens up a whole new world of possibilities. Utilizing the DI system, we can create reusable functions. I like to call it a DI function:

For example:

Here’s one more example that returns an observable based on the timespan query parameter:

Angular has also added a hook named onDestroy to a ViewRef where we can register our cleanup logic. Thus, we can now create powerful things such as untilDestroyed:

We can also leverage the NodeInjector:

It can be used to provide a more clean and robust approach for library authors:

It is undoubtedly a very powerful feature, but let’s look at the cons as well.

First, inject() can only be called in the constructor, so we can’t leverage a component’s inputs. We can work around it by using closures, but did we gain anything?

Secondly, it makes testing harder. I don’t mind since I work directly with Cypress and don’t mock anything, but it might be an issue in your case.

And last but not least, it might feel like magic (similar to React hooks), and I’m not too fond of magic, unlike my children 😄

Closing Thoughts

It is a very exciting feature. I am still not sure how I feel about it, but we will have to wait and see where the community takes it.

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.