2017-05-26 61 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

回答