在ngAfterViewInit中调用时,ViewContainerRef是未定义的

时间:2018-09-21 15:12:43

标签: angular angular6 viewchild

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

1 个答案:

答案 0 :(得分:2)

由于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