inheritance - angular2 扩展组件但保留模板

标签 inheritance angular

有没有办法扩展/继承 angular2 组件?

假设(为了简单起见)我有一个 Button 组件。基于此组件,我想将其扩展为 RedButton 组件,但使用相同的模板和初始化方法,但仅更改用户按下按钮时发生的情况。这怎么可能?


到目前为止,这是我尝试过的:

按钮.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');
    }
}

应用程序组件.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 { }

最佳答案

(目前?)不支持扩展类和继承模板。您可以做的是使用 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})])

输入和输出需要额外的接线,因此不太方便但可行。

关于inheritance - angular2 扩展组件但保留模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35583012/

相关文章:

angularjs - Angular CLI + Webpack + i18n 模块集成

javascript - 使用 this.inherited 在 dojo 中调用祖 parent 方法

java - 多级继承: Calling a method only ONE level higher from subclass

java - 带有继承方法的Spring hateoas methodOn

javascript - Object.create 是否也创建自己的属性

angular - 如果找不到数据,则解析 Guard : Proper way to resolve observable from Routes,

Java:当对象被声明为基类时访问派生类的成员

android - angular 在 href 中的 url 之前添加不安全 - 清理不安全的 URL

angular - 如何将 Angular Material 组件正确导入 StoryBook CSF

angular - 如何使用 angular 7 在 strip 网关中添加计费和运输字段