2

based on this stack overflow post (Angular Dynamic Components: @ViewChildren get ViewContainerRef for every component in QueryList), I'm trying to add dynamic component in an ngFor.

The issue is that the ViewChildred referencing the ng template is always undefined

Here my template

<div *ngFor="let service of loadedServices; let i = index;">
  <accordion [closeOthers]="true">
    <accordion-group panelClass="b0 mb-2">
      <div accordion-heading>
        <small>
          <em class="fa fa-plus text-primary mr-2"></em>
        </small>
        <span><b>{{service.description}}</b></span>
      </div>

      <ng-template #serviceBookmark></ng-template>


    </accordion-group>
  </accordion>
</div>

Here my component

export class DatasourceDetailsComponent implements OnInit,AfterContentInit  {
constructor(private resolver: ComponentFactoryResolver) { }

@ViewChildren('serviceBookmark', { read: ViewContainerRef })
public dynComponents: QueryList<ViewContainerRef>;

ngAfterContentInit() {
    this.dynComponents.map(
      (vcr: ViewContainerRef, index: number) => {
        const factory = 
    this.resolver.resolveComponentFactory(ServiceFormComponent);
    vcr.createComponent(factory);
  }
);
}
}

Unfortunately in AfterContentInit the dynComponent is always undefined... What I'm doing wrong?

Thanks

Davide.77
  • 165
  • 2
  • 12

1 Answers1

1

You should try with ngAfterViewInit or a setter:

components: QueryList<ViewContainerRef>;

@ViewChildren('serviceBookmark', { read: ViewContainerRef })
set dynComponents(comps: QueryList<ViewContainerRef>) {
    console.log(comps);
    this.components = comps;
}

This should work.

tano
  • 2,657
  • 1
  • 15
  • 16
  • there is probably an issue... comps is a ViewContainerRef in your sample... and dynComponents is defined as QueryList... It gives me error... could you please help me? I'm new to angular. thanks – Davide.77 Sep 23 '19 at 09:43
  • Sorry, I've fixed the example – tano Sep 23 '19 at 09:50