ViewContainerRef не определен при вызове в ngAfterViewInit - PullRequest
0 голосов
/ 21 сентября 2018

Я хочу динамически создать дочерний компонент при инициализации родительского компонента, но когда я попытался создать его в 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 голосов
/ 21 сентября 2018

Поскольку 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);
}

См. этот стек для демонстрации.

...