首页 > 解决方案 > 在 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>
...

标签: angularangular6viewchild

解决方案


由于 位于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以获取演示。


推荐阅读