在ngAfterViewInit中调用时,ViewContainerRef是未定义的 [英] ViewContainerRef is undefined when called in ngAfterViewInit
问题描述
我想在初始化父组件时动态创建一个子组件,但是当我尝试在ngAgterViewInit()中创建子组件时,它抛出了ViewContainerRef未定义的错误.
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.
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>
...
推荐答案
由于div
在ngIf
条件块内,因此在ngAfterViewInit
中可能不可用.您可以通过使用ViewChildren
和QueryList.changes
事件监视元素的存在来保护代码,以防止这种情况的发生:
Since the div
is inside an ngIf
conditional block, it may not be available in ngAfterViewInit
. You can protect the code against that possibility by monitoring the presence of the element with ViewChildren
and the QueryList.changes
event:
@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);
}
有关演示,请参见此stackblitz .
这篇关于在ngAfterViewInit中调用时,ViewContainerRef是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!