2017-10-28 38 views
3

只是試圖澄清ViewContainerRef.createComponent索引參數的含義:ViewContainerRef(索引參數)

createComponent<C>(
    componentFactory: ComponentFactory<C>, 
    index?: number, 
    injector?: Injector, 
    projectableNodes?: any[][], 
    ngModule?: NgModuleRef<any> 
): ComponentRef<C> 

讓審查索引參數: 我創建了小例子 https://plnkr.co/edit/sbDomj 我建立索引作爲0.沒關係。這個例子的作品。但是,如果您更改此值(1),則組件不會被添加。爲什麼?這個參數的反應是什麼?

回答

3

您可以將多個組件添加到ViewContainerRef的hostView。

默認(沒有指定索引)表示新組件添加在列表的末尾。

如果指定了索引,則新組件插入該位置。如果添加了一個無效位置(1對於空列表無效),那麼您將獲得所描述的行爲。 如果列表已經包含2個組件,那麼1將是一個有效的索引,並且您的調用將在第一個和第二個之間插入組件。

又見https://angular.io/api/core/ViewContainerRef#createComponent

Plunker example