This content originally appeared on Bits and Pieces - Medium and was authored by Arthur Groupp

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
Bit: Build Better UI Component Libraries
Say hey to Bit. It’s the #1 tool for component-driven app development.
With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.
- Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
- Easily share, and reuse components as a team.
- Quickly update components across projects.
- Make hard things simple: Monorepos, design systems & micro-frontends.

Learn more
- How We Build Micro Frontends
- How we Build a Component Design System
- The Bit Blog
- 5 Ways to Build a React Monorepo
How to Extend Components, Directives and Services in Angular 14 was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Arthur Groupp

Arthur Groupp | Sciencx (2022-09-06T11:38:38+00:00) How to Extend Components, Directives and Services in Angular 14. Retrieved from https://www.scien.cx/2022/09/06/how-to-extend-components-directives-and-services-in-angular-14/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.