有没有办法从angular2组件扩展/继承?
让我们说(为了简单起见)我有一个Button
组件。基于此组件,我想将其扩展为RedButton
组件,但使用相同的模板和初始化方法,但只更改用户按下按钮时发生的情况。这怎么可能?
这是我到目前为止所尝试的内容:
button.component.ts
import {Component, View} from 'angular2/core';
@Component({
selector : 'my-button'
})
@View({
template : '<button (click)="clicked()">Click</button>'
})
export class ButtonComponent {
constructor() {
}
public clicked(event) {
console.log('Base clicked');
}
}
redbutton.component.ts
import {Component, View} from 'angular2/core';
import {ButtonComponent} from './button.component';
@Component({
selector : 'my-redbutton'
})
// typescript complaints here, that RedButton needs a View and template
export class RedButtonComponent extends ButtonComponent {
constructor() {
super();
}
public clicked(event) {
console.log('RED clicked');
}
}
app.component.ts
import {Component} from 'angular2/core';
import {ButtonComponent} from './button.component';
import {RedButtonComponent} from './redbutton.component';
@Component({
selector: 'coach-app',
directives : [ButtonComponent, RedButtonComponent],
template: '<h1>Button Test App</h1><my-button></my-button><my-redbutton></my-redbutton>'
})
export class TestAppComponent { }
答案 0 :(得分:1)
不支持扩展类和继承模板(目前?)。您可以做的是使用DI来配置组件。
interface ButtonBehavior {
component:any;
onClick(event);
}
class DefaultButtonBehavior implements ButtonBehavior {
component:any;
onClick(event) {
console.log('default button clicked');
}
}
class FancyButtonBehavior implements ButtonBehavior {
component:any;
onClick(event) {
console.log('default button clicked');
}
}
class ButtonComponent {
constructor(private buttonBehavior:ButtonBehavior) {
buttonBehavior.component = this.
}
}
bootstrap(AppComponent, [provide(ButtonBehavior, {useClass: FancyButtonBehavior})])
输入和输出需要额外的布线,因此不太方便但可行。