Davide.77
Davide.77

Reputation: 315

Angular Dynamic component ViewChildren always undefined

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

Upvotes: 2

Views: 1323

Answers (1)

tano
tano

Reputation: 2817

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.

Upvotes: 1

Related Questions