Dynami c Компоненты не работают при загрузке после ViewInit - PullRequest
0 голосов
/ 01 апреля 2020

Почему не работает следующий код? Почему @ViewChildren не может обнаружить ng-container с?

HTML

<div [innerHtml]="html"></div>

Контроллер:

import { Component, ViewChildren, AfterViewInit, QueryList,ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChildren('helloComponent',{read: ViewContainerRef}) components: QueryList<ViewContainerRef>

  html = "<ng-container #helloComponent></ng-container><ng-container #helloComponent></ng-container>";

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver, 
    private injector: Injector
  ){

  }

  ngAfterViewInit() {
     var i = 0;
     this.components.forEach(hello => {
       const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
       var componentRef = hello.createComponent(componentFactory);
       componentRef.instance.name = i.toString();
        i++;
     });

  }
}

Вот демоверсия: https://stackblitz.com/edit/angular-8-dynamic-components-not-working

1 Ответ

0 голосов
/ 01 апреля 2020

@ ViewChildren должен ссылаться на родителя с детьми внутри него:

<ng-container #helloComponents>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
</ng-container>
...