2016-02-23 24 views
5

Có cách nào để mở rộng/kế thừa từ các thành phần angular2 không?angular2 mở rộng thành phần nhưng giữ mẫu

Giả sử (vì mục đích đơn giản), tôi có thành phần Button. Dựa trên thành phần này, tôi muốn mở rộng nó thành một thành phần RedButton nhưng sử dụng cùng một khuôn mẫu và phương thức khởi tạo nhưng chỉ thay đổi những gì xảy ra khi người dùng nhấn nút. Sao có thể như thế được?


Đây là những gì tôi đã cố gắng cho đến nay:

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

Trả lời

1

Mở rộng lớp và kế thừa mẫu là (hiện tại?) Không được hỗ trợ. Những gì bạn có thể làm là sử dụng DI để cấu hình thành phần của bạn.

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

Đầu vào và đầu ra sẽ cần thêm dây, do đó không thuận tiện nhưng có thể thực hiện được.

Các vấn đề liên quan