DEV Community

Cover image for Extending components, directives and services in Angular 14
Arthur Groupp
Arthur Groupp

Posted on

Extending components, directives and services in Angular 14

First, avoid it as much as possible. Extending components by itself is bad practice because it’s confusing code and adds more issues than actually helps. However, sometimes it can be helpful to combine common logic of similar components or directives into abstract class that they all will extend.

Let’s say, we have two components like this:

Of course, these components can be combined into one, but let’s assume that this is not the case and they have much more logic and templates specific to each.

Let’s modify our components and put shared logic into abstract base class that they will extend.


Much DRYer. The problem with this approach is dependencies. Since our base class has dependencies, it can’t inject it by itself because it doesn’t exist. Therefore, we must inject all those dependencies by ourselves in child classes and supply it to super().

Inject function

Starting with version 14 of Angular we can use function inject() to obtain instances of injection tokens in other functions, components, services, almost everywhere. This opens us great possibility to avoid repeating of these injections in derived classes. From now on, we can add static method to our base class that will initialize its dependencies.

Conclusion

I widely use abstractions and this feature excited me much. I was looking for the ability to avoid manual injections for a long time and now here it is.

Photo by Andrew Seaman on Unsplash

Top comments (0)