2017-07-08 32 views
2

我想创建角4获取ViewContainerRef从组件

嵌套的组件,这是选配组件

import {InputComponent} from './input/input.component' 
import {BlockComponent} from './block/block.component' 

export const FormChooser = { 
    Block: BlockComponent, 
    Input: InputComponent 
} 

这是组件制造商

const component = FormChooser[data.component] 
const factory = this.Resolver.resolveComponentFactory(component) 

const new_component = this.ViewContainerRef.createComponent(factory) 

如何获得new_component ViewContainerRef?这样我就可以使用这样的代码

const another_new_component = new_component.createComponent(factory) // as ViewContainerRef 

谢谢...

+0

@yurzui已经做了,那'this.ViewContainerRef'是ViewContainerRef从构造函数注入,但我无法从该组件找到任何ViewContainerRef –

+0

文章[这里是如何在评估@ViewChild查询之前获取ViewContainerRef](https://hackernoon.com/here-is-how-to-get -viewcontainerref-before-viewchild-query-is-evaluate-f649e51315fb)显示了如何完成这项工作 –

+0

,并且您是否希望'InputComponent'成为'BlockComponent'的子项?因为如果你按照你的要求去做,你最终会遇到这种情况。他们不会是兄弟姐妹 –

回答

1

您可以在动态组件的构造

class BlockComponent { 
    constructor(public vcRef: ViewContainerRef) {} 
} 

const factory = this.Resolver.resolveComponentFactory(BlockComponent) 

const newComponentRef = this.ViewContainerRef.createComponent(factory); 
const newComponentVcRef = newComponentRef.instance.vcRef; 

注入ViewContainer或使用@ViewChild获得参考ViewContainerRef

template: '<ng-container #ref></ng-container>' 
}) 
class BlockComponent { 
    @ViewChild('ref) vcRef: ViewContainerRef; 
} 

const factory = this.Resolver.resolveComponentFactory(BlockComponent) 

const newComponentRef = this.ViewContainerRef.createComponent(factory); 
const newComponentVcRef = newComponentRef.instance.vcRef; 
+0

中描述的方法进行操作,感谢它的工作,将ViewContainerRef放入该块组件中,以便我可以从实例.. –