在 ngAfterViewInit 中调用时 ViewContainerRef 未定义

ViewContainerRef is undefined when called in ngAfterViewInit

我想在父组件初始化时动态创建一个子组件,但是当我尝试在 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>
...

由于 divngIf 条件块内,它可能在 ngAfterViewInit 中不可用。您可以通过使用 ViewChildrenQueryList.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