[英]ViewContainerRef is undefined when called in ngAfterViewInit
I want to dynamically create a child component when the parent component is initialised, but when I tried to create it in ngAgterViewInit(), it throws the error that the ViewContainerRef is undefined. 我想在父组件初始化时动态创建子组件,但是当我尝试在ngAgterViewInit()中创建子组件时,它引发了ViewContainerRef未定义的错误。
component.ts component.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 component.html
...
<div class="row" #container ></div>
...
Since the div
is inside an ngIf
conditional block, it may not be available in ngAfterViewInit
. 由于div
是一个内部ngIf
条件块,它可能不是可用ngAfterViewInit
。 You can protect the code against that possibility by monitoring the presence of the element with ViewChildren
and the QueryList.changes
event: 您可以通过使用ViewChildren
和QueryList.changes
事件监视元素的存在来保护代码避免这种可能性:
@ViewChildren('container', { read: ViewContainerRef }) containers: QueryList<ViewContainerRef>;
ngAfterViewInit() {
if (this.containers.length > 0) {
// The container already exists
this.addComponent();
};
this.containers.changes.subscribe(() => {
// The container has been added to the DOM
this.addComponent();
});
}
private addComponent() {
const container = this.containers.first;
const factory = this.resolver.resolveComponentFactory(ChildComponent);
container.createComponent(factory);
}
See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.