angular - 在 ngAfterViewInit 中调用 ViewContainerRef 时未定义
问题描述
我想在父组件初始化时动态创建一个子组件,但是当我尝试在 ngAgterViewInit() 中创建它时,它会抛出 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
:
@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以获取演示。
推荐阅读
- angular - Angular domSanitizer 绕过属性之外的SecurityTrustHtml
- reactjs - 使用箭头函数作为数据服务
- reactjs - 如何使用材质 ui 在复杂网格中将容器/项目居中
- db2 - 如何检查 DB2 表中的无效日期
- python-3.x - Python删除输入行
- unity3d - Unity Video Player如何获取当前显示的帧?
- cygwin - .txt 文件中变量的 Grep 压缩文件
- android-studio - Flutter Android studio 使用所有内存
- amazon-web-services - 在 aws lambda 中重试外部 API 超时
- go - 使用 go 通道使结构线程安全