【发布时间】:2019-02-26 00:53:24
【问题描述】:
我想在父组件初始化的时候动态创建一个子组件,但是当我尝试在ngAgterViewInit()中创建它时,它会抛出ViewContainerRef未定义的错误。
组件.ts
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {
}
ngAfterViewInit(){
const factory = this.resolver.resolveComponentFactory(ChildComponent);
this.container.createComponent(factory); //container is undefined here
}
component.html
...
<div class="row" #container ></div>
...
【问题讨论】:
-
div是否在ngIf条件块内? -
代码本身运行正常,刚刚试了一下。
-
@ConnorsFan,是的,它在 ngIf 中
标签: angular angular6 viewchild