Angular2 Component Inheritance Summary

Simple tutorial can be found here at Component Inheritance in Angular 2

There are some limitations.

  1. No Annotations inheritance. More detail on Angular 2, decorators and class inheritance

    Which means, no template or style inheritance.

  2. Constructor inheritance relies on child component re-injection. More detail on Github discussion

    Also the inject variable should set as protected or public.

re-injection
1
2
3
4
5
6
7
8
9
10
export class ChildCmp extends BaseCmp {
constructor(protected http: Http) {
super(http);
}
...
}

  1. Lifecycle hooks needs to be called manually if derive class overwrites it.

    It can be called like

re-injection
1
2
3
4
5
6
7
8
9
10
11
export class ChildCmp extends BaseCmp {
ngOnDestroy() {
super.ngOnDestroy();
...
}
...
}

However, here is a small hack to ensure parent's ngOnDestroy always get called. Using Class inheritance to hook to Angular 2 component lifecycle

hack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export class SafeUnsubscriber implements OnDestroy {
private subscriptions: Subscription[] = [];
constructor() {
let f = this.ngOnDestroy;
this.ngOnDestroy = () => {
f();
this.unsubscribeAll();
};
}
protected safeSubscription (sub: Subscription): Subscription {
this.subscriptions.push(sub);
return sub;
}
private unsubscribeAll() {
this.subscriptions.forEach(element => {
!element.isUnsubscribed && element.unsubscribe();
});
}
ngOnDestroy() {
// no-op
}
}