我想在初始化父组件时动态创建子组件,但是当我尝试在ngAgterViewInit()中创建子组件时,会引发错误,即ViewContainerRef未定义。
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>
...
答案 0 :(得分:2)
由于div
在ngIf
条件块内,因此在ngAfterViewInit
中可能不可用。您可以通过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);
}
有关演示,请参见this stackblitz。