2017-05-11 19 views
3

我有3個組件。 1個父組件,它可以將任何2個子組件中的一個子組件包裝在ng內容中。我的子組件具有共享功能,因此它們擴展了具有共享功能的抽象類。擴展類的Angular ContentChildren

當我嘗試使用ContentChildren獲取ng內容引用時,如果我使用其中一個子類,它工作正常。當我參考抽象類時,它不起作用。有沒有辦法做到這一點? plkr是:http://plnkr.co/edit/f3vc2t2gjtOrusfeesHa?p=preview

這裏是我的代碼:

兒童抽象類:

abstract export class Child{ 
     value: any; 
     abstract setValue(); 
    }  

我父代碼:

@Component({ 
    selector: 'parent', 
    template: ` 
    <div> 
     parent 
     <ng-content></ng-content> 
    </div> 
    `, 
}) 
export class Parent { 
    @ContentChild(Child) 
    child: Child; 
    name:string; 
    constructor() { 

    } 
    ngAfterViewInit() { 
    this.child.setValue(); 
    } 
} 

第一個孩子:

@Component({ 
    selector: 'child1', 
    template: ` 
    <div> 
     value is: {{value}} 
    </div> 
    `, 
}) 
export class Child1 extends Child { 
    name:string; 
    constructor() { 

    } 
    setValue() {this.value = 'Value from child 1'} 
} 

二兒童:

@Component({ 
    selector: 'child2', 
    template: ` 
    <div> 
     value is: {{value}} 
    </div> 
    `, 
}) 
export class Child2 extends Child { 
    name:string; 
    constructor() { 

    } 
    setValue() {this.value = 'Value from child 2'} 
} 

回答

5

我解決了這個利用:

到我的組件裝飾爲Child1

providers: [{provide: Child, useExisting: forwardRef(() => Child1)}], 

到我的組件裝飾的CHILD2

providers: [{provide: Child, useExisting: forwardRef(() => Child2)}], 

現在,您可以看看來自角度的新io示例:

https://angular.io/guide/dynamic-component-loader