问题描述
问题
我想为已部署在Angular 2中的某些组件创建扩展,而不必像几乎完全重写它们一样,基本组件可能会发生变化,并希望这些变化也反映在其衍生组件中。
I would like to create extensions for some components already deployed in Angular 2, without having to rewrite them almost completely, as the base component could undergo changes and wish these changes were also reflected in its derived components.
示例
我创建了这个简单的示例,试图更好地解释我的问题:
使用以下基本组件 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
:
Would you like to create another derivative component only alter, for example, a basic component behavior in the case of the example 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";
}
}
问题
正如你在衍生组件的实现中看到的那样 app / my-panel.component.ts
,大部分实现都重复了,单个部分真正继承的是类
BasePanelComponent
,但 @Component
基本上必须完全重复,而不仅仅是更改的部分,因为选择器:'my-panel'
。
As you can see in the implementation of the derivative component app/my-panel.component.ts
, much of the implementation was repeated, and the single part really inherited was the class
BasePanelComponent
, but the @Component
had to basically be completely repeated, not just the changed portions, as the selector: 'my-panel'
.
问题
以某种方式实现字面上的完全继承组件Angular2,继承类
标记/注释的定义,例如 @Component
?
To some way to make a literally full inheritance of a component Angular2, inheriting the class
definition of the markings/annotations, as for example @Component
?
编辑1 - 功能请求
编辑2 - 已关闭请求
推荐答案
Angular 2版本2.3刚刚发布,它包含本机组件继承。看起来你可以继承和覆盖你想要的任何东西,模板和样式除外。一些参考文献:
Angular 2 version 2.3 was just released, and it includes native component inheritance. It looks like you can inherit and override whatever you want, except for templates and styles. Some references:
这篇关于如何扩展/继承Angular2组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!