2017-02-15 82 views
1

我有三個組件,其中componentC作爲componentB的內容出現,並在其構造函數中獲得componentB DI'ed。DI和transclusion

@Component({ 
    selector: 'componentA', 
    template: ` 
    <componentB> 
     <componentC></componentB> 
     <ng-content></ng-content> 
    </componentB>` 
.... 
export class ComponentC { 
    constructor(private cmpB: ComponentB) 

現在我用componentA從另一個組件,並希望通過我把在componentA的模板<ng-content>使用transclusion提供額外componentC s到它:

<componentA> 
    <componentC></componentC> 
</componentA> 

這會觸發No provider for ComponentB。使用<ng-content>,我定義內容應該出現在<componentB>之內,因此DI應該能夠找到作爲插入點的父對象的ComponentB對象。

這種情況可能嗎? Angular會直接在目標位置創建額外的ComponentC,還是首先在標記處移動它?有沒有辦法配置供應商來做到這一點?

回答

0

的transclusion不作componentCcomponentB一個孩子,它保持的componentA孩子,只是其中示內的DOM發生改變。

我沒有看到一個簡單的方法來使注射工作。

你可以做componentA提供其中componentA分配給componentB

@Component({ 
    ... 
    providers: [ComponentBProviderService], 
class ComponentA { 
    @ViewChild(ComponentB) componentB:ComponentB; 
    constructor(private bProvider: ComponentBProviderService){} 
    ngAfterViewInit() { 
    this.bProvider.component = this.componentB; 
    } 
} 

時的參考ComponentC注入該服務將得到componentB訪問的服務。 在服務中使用Observable將有意義,當參考變得可用時主動通知componentC

class ComponentC { 
    componentB:ComponentB; 
    constructor(bProvider: ComponentBProviderService){ 
    bProvider.componentAvailable.subscribe(val => this.componentB = val); 
    } 
} 
+1

有關跨越不改變組件層次結構的好處,但只是移動DOM的東西。 會有另一種解決方案使用模板和組件工廠來實例化內容作爲'componentB'的子項嗎? – achimha