Angular4 Components inheritance with abstract class Angular4 Components inheritance with abstract class angular angular

Angular4 Components inheritance with abstract class


Update for Angular 10+

As of Angular 10, when using the IVY compiler, components that are inherited, and which contain Angular functionality, must be decorated with an empty @Directive() decorator.

Read more about it here


There's no need to add @Component() annotations to abstract classes or register them to any module.

It could be that there's something wrong within your code that does not conform to what Angular expects.

I created a demo application using Angular CLI 1.2.7 with the ng new <name> command and extend the AppComponent class as below.

base.component.ts

import { HostListener } from '@angular/core';export abstract class BaseComponent {    @HostListener('click')    onClick() {        alert('Click');    }}

and

app.component.ts

import { Component } from '@angular/core';import { BaseComponent } from './base.component';@Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: [ './app.component.css' ]})export class AppComponent extends BaseComponent {    title = 'app';}

The app.module class was not changed in any way.

The click handler located in the base component worked without any problems. A AOT compilation using ng build --prod also did not give any errors.

This demo was using angular v5.1.1