Member-only story
Angular: Inheritance Without Effort
A great way of using inheritance in our app without maintenance

Written in TypeScript, Angular makes it possible to use the concept of inheritance in our components.
However, we face a problem when we want services in child components.
Getting Started
Let’s start by creating our BaseComponent
:
See that the decorator Component
is not necessary — we don’t have to declare this class in the module, as it is not a component. We can also declare it as an abstract class as we would do in regular OOP language.
Then, we create our two components extended by the BaseComponent
:
When we navigate from one component to another, the logs are correctly printed in the console.
Our child components are now ready!
However, in the AComponent
, I would like to access its ElementRef
(or another service):
And here is our problem. When I want to inject ElementRef
in that component, I have to call the method super()
and pass our two other classes. Imagine, if you have other services in the BaseComponent
, it will be hard to manage the children.
If I add or remove a service in BaseComponent
, I have to reflect these changes in every child component extended by it.
Fortunately, there is a solution which is easy to implement. We will inject our services into the BaseComponent
…