2017-05-26 59 views
1

我有一個部件:ViewContainerRef&createEmbeddedView澄清?

@Component({ 
    selector: 'vcrdi', 
    template: ` 
    <template #tpl> 
     <h1>ViewContainerRef DI</h1> 
    </template> 

    `, 
}) 
export class VcrDIComponent { 
    @ViewChild('tpl') tpl; 

    constructor(private _vcr: ViewContainerRef) {console.log(_vcr)} 

    ngAfterViewInit() { 
    this._vcr.createEmbeddedView(this.tpl); 
    } 
} 

該組件在主my-app元件用作:在vcrdi組分被注入_vcr: ViewContainerRef

@Component({ 
    selector: 'my-app', 
    template: ` 
     <vcrdi></vcrdi> 
    `, 
}) 

的CTOR所以現在的容器是實際<vcrdi>...</vcrdi>元件。

這是呈現的DOM:

enter image description here

注意,h1插入的ViewContainerRef後(這是vcrdi元素)

讓我們去docs

createEmbeddedView(templateRef: TemplateRef<C>, context?: C, index?: number) : EmbeddedViewRef<C>
基於templateRef實例化嵌入式視圖,並且將其插入指定的 索引處的容器

如果未指定索引,則新視圖將作爲最後的 視圖插入容器中。

好吧,如果vcrdi是容器裁判的話,我沒有看到任何東西注入到它:

<vcrdi> 
    // If vcrdi^is the container , then why does this section empty ? 
</vcrdi> 

問:

的文檔指出,事情是在注入容器。
但是,如果vcrdi是容器,並且我們看到沒有任何注入 - 但附加 - 然後 - 我在這裏錯過了什麼?

Demo PLNKER

回答