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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

there is probably an issue... comps is a ViewContainerRef in your sample... and dynComponents is defined as QueryList<ViewContainerRef>... It gives me error... could you please help me? I'm new to angular. thanks
Sorry, I've fixed the example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.