My goal is to develop extensions for existing Angular 2 components without having to completely rewrite them. I want any changes made to the base component to also automatically apply to its derived components.
To illustrate my point, consider the following scenario:
We have a base component called app/base-panel.component.ts
:
import {Component, Input} from 'angular2/core';
@Component({
selector: 'base-panel',
template: '<div class="panel" [style.background-color]="color" (click)="onClick($event)">{{content}}</div>',
styles: [`
.panel{
padding: 50px;
}
`]
})
export class BasePanelComponent {
@Input() content: string;
color: string = "red";
onClick(event){
console.log("Click color: " + this.color);
}
}
Now, let's say we want to create a derivative component, app/my-panel.component.ts
, where we only need to change one basic behavior of the base component, such as the color:
import {Component} from 'angular2/core';
import {BasePanelComponent} from './base-panel.component'
@Component({
selector: 'my-panel',
template: '<div class="panel" [style.background-color]="color" (click)="onClick($event)">{{content}}</div>',
styles: [`
.panel{
padding: 50px;
}
`]
})
export class MyPanelComponent extends BasePanelComponent{
constructor() {
super();
this.color = "blue";
}
}
View complete working example in Plunker
This example is simplistic but highlights the challenge of inheriting components in Angular 2 effectively without excessive repetition.
In the implementation of the derivative component app/my-panel.component.ts
, much of the code was duplicated, and only the class
BasePanelComponent
was truly inherited. The @Component
decorator had to be duplicated entirely, including the parts that remained unchanged, like selector: 'my-panel'
.
I'm wondering if there is a way to fully inherit a component in Angular 2, preserving the annotations like @Component
without repeating them.
Edit 1 - Feature Request
I submitted a feature request on GitHub: Extend/Inherit angular2 components annotations #7968
Edit 2 - Closed Request
The request has been closed due to technical limitations, as detailed here. Unfortunately, it seems merging decorators for inheritance might not be feasible, leaving us with limited options. I shared my thoughts on this issue in the comments.