我想为 Angular 2 中已经部署的一些组件创建扩展,而不必几乎完全重写它们,因为基础组件可能会发生更改,并希望这些更改也反映在其派生组件中。
我创建了这个简单的示例来尝试更好地解释我的问题:
具有以下基本组件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);
}
}
您是否想创建另一个仅改变示例颜色情况下的基本组件行为的派生组件,app/my-panel.component.ts
:
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";
}
}
Plunker 中的完整工作示例 http://plnkr.co/edit/bWa1JmH7NaSaJffLsl0x?p=preview
注意:显然这个例子很简单,可以解决,否则不需要使用继承,但它只是为了说明真正的问题。
正如您在衍生组件的实现中所看到的app/my-panel.component.ts
,大部分实现都是重复的,真正继承的部分是class
BasePanelComponent
,但是@Component
基本上必须完全重复,而不仅仅是改变的部分,因为selector: 'my-panel'
.
有没有某种方法可以完全继承 Angular2 组件,继承class
标记/注释的定义,例如@Component
?
编辑 1 - 功能请求
将功能请求 angular2 添加到 GitHub 上的项目中:扩展/继承 angular2 组件注释 #7968 https://github.com/angular/angular/issues/7968
编辑 2 - 已关闭的请求
请求已关闭,为此原因 https://github.com/angular/angular/issues/7968#issuecomment-219865739,短暂地不知道如何合并装饰器。让我们别无选择。所以我的意见是本期引用 https://github.com/angular/angular/issues/7968#issuecomment-222496110.