简体   繁体   中英

angular2 extend component but keep template

Is there a way to extend/inherit from angular2 components?

Let's say (for the sake of simplicity) I have a Button component. Based on this component I want to extend it to a RedButton component but use the same template and initialization methods but only change what happens when the user presses the button. How is this possible?


Here is what I tried so far:

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 { }

Extending classes and inheriting the template is (currently?) not supported. What you could do is using DI to configure your component.

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})])

Inputs and outputs would need additional wiring, therefore not too convenient but doable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM