2017-08-28 87 views
2

我有分量的層次結構:Angular 4 - 如何訪問模板內部的嵌套組件?

App 
| 
Child 
| 
Input 

組件「兒童」接受一個模板從它的父這樣的:

<my-child> 
    <ng-template> 
     <my-input></my-input> 
     <span>asdasdas</span> 
     <my-input></my-input> 
     <my-input></my-input> 
    </ng-template>  
</my-child> 

正如你可以在模板中看到有一些輸入組件。現在我想要訪問子組件列表中的<my-input>組件列表。我現在嘗試的是使用@ ContentChildren/@ ViewChildren,但它似乎不工作。兒童組件的代碼:

@Component({ 
    selector: 'my-child', 
    providers: [], 
    template: ` 
    <div> 
     <ng-template [ngTemplateOutlet]="inputTemplate" #input></ng-template> 
    </div> 
    `, 
    directives: [] 
}) 

export class Child implements OnInit, OnAfterViewInit { 

    @ContentChild(TemplateRef) inputTemplate: TemplateRef<any>; 

    @ViewChildren(InputComponent) inputComponents : QueryList<InputComponent>; 

    constructor() { 

    } 

    ngAfterViewInit(){ 
    //THIS SHOULD NOT BE EMPTY 
    console.log(this.inputComponents.toArray()); 
    } 
} 

請讓我知道我做錯了什麼,以及如何/是否有可能獲得由兒童組成InputComponents的列表。

也許我不應該在這裏使用模板?有沒有其他方法可以使此控件可定製,並仍然可以訪問嵌套的InputComponents列表?

如果你想用它here's the plunker

回答

4

使用@ContentChildren(InputComponent)代替@ViewChildren()和訂閱變化

ngAfterViewInit(){ 
    //THIS SHOULD NOT BE EMPTY 
    this.inputComponents.changes.subscribe(c => console.log(this.inputComponents.toArray())); 
    //console.log(this.inputComponents.toArray()); 
    } 

工作對我來說玩,但老實說,我不知道自己爲什麼@ContentChildren()代替@ViewChildren()正在工作。

Plunker link

+1

'ViewChildren'不起作用,因爲內容DOM(在視圖中不DOM)內組件 –

+0

TemplateRef使用ContentChild也必然和它的作品。我不知道訂閱變更的能力。據我所知,它應該已經綁定在ngAfterViewInit中,但是由於這些組件嵌套在模板中,我認爲它實際上是在後面發生的。感謝您的解決方案! – kubal5003

+0

是的,但'TemplateRef'實際上被傳遞了內容,但是模板被渲染到了組件中,並且我期望創建的組件成爲子組件。是的,這就是原因。在ngOnInit或ngAfterViewInit中只有'TemplateRef'可用,'ngTemplateOutlet'只在這個變化檢測週期完成後呈現。 –