【问题标题】:ViewContainerRef is undefined when called in ngAfterViewInit在 ngAfterViewInit 中调用 ViewContainerRef 时未定义
【发布时间】:2019-02-26 00:53:24
【问题描述】:

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

  }

component.html

...
<div class="row" #container ></div>
...

【问题讨论】:

标签: angular angular6 viewchild


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2019-06-23
    • 2021-02-18
    • 2018-02-12
    • 2019-08-07
    • 2020-02-04
    • 2018-06-28
    • 1970-01-01
    • 2017-09-28
    相关资源
    最近更新 更多