Better Programming

Advice for programmers.

Follow publication

Member-only story

Angular: Inheritance Without Effort

Kevin MATHY
Better Programming
Published in
4 min readJul 29, 2019
Photo by Jakub Gorajek on Unsplash

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Kevin MATHY
Kevin MATHY

Written by Kevin MATHY

Web developer & Angular Specialist

Responses (7)

Write a response