我想在父组件初始化时动态创建子组件,但是当我尝试在 ngAfterViewInit() 中创建它时,它会抛出 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
}
组件.html
...
<div class="row" #container ></div>
...
自从div
是在一个ngIf
条件块,它可能不可用ngAfterViewInit
。您可以通过监视元素的存在来保护代码免受这种可能性的影响ViewChildren
和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 这次堆栈闪电战 https://stackblitz.com/edit/angular-n61rj6进行演示。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)