ViewContainerRef 在 ngAfterViewInit 中调用时未定义 [英] ViewContainerRef is undefined when called in ngAfterViewInit
问题描述
我想在初始化父组件时动态创建子组件,但是当我尝试在 ngAgterViewInit() 中创建它时,它抛出 ViewContainerRef 未定义的错误.
component.ts
@ViewChild('container', {read: ViewContainerRef}) 容器:ViewContainerRef;构造函数(私有解析器:ComponentFactoryResolver){}ngAfterViewInit(){const factory = this.resolver.resolveComponentFactory(ChildComponent);this.container.createComponent(工厂);//此处未定义容器}
component.html
<预><代码>...<div class="row" #container ></div>...由于 div
在 ngIf
条件块内,它可能在 中不可用ngAfterViewInit
.您可以通过使用 ViewChildren
和 QueryList.changes
事件监视元素的存在来保护代码免受这种可能性的影响:
@ViewChildren('container', { read: ViewContainerRef }) 容器:QueryList;ngAfterViewInit() {如果(this.containers.length > 0){//容器已经存在this.addComponent();};this.containers.changes.subscribe(() => {//容器已经添加到 DOMthis.addComponent();});}私人添加组件(){const 容器 = this.containers.first;const factory = this.resolver.resolveComponentFactory(ChildComponent);container.createComponent(工厂);}
有关演示,请参阅此 stackblitz.
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
@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>
...
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);
}
See this stackblitz for a demo.
这篇关于ViewContainerRef 在 ngAfterViewInit 中调用时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!